fs: how do I locate a parent folder?


How do I write this to go back up the parent 2 levels to find a file?

fs.readFile(__dirname + 'foo.bar');
12/4/2015 1:10:39 AM

Accepted Answer

Try this:

fs.readFile(__dirname + '/../../foo.bar');

Note the forward slash at the beginning of the relative path.

7/26/2016 8:45:05 PM

Use path.join http://nodejs.org/docs/v0.4.10/api/path.html#path.join

var path = require("path"),
    fs = require("fs");

fs.readFile(path.join(__dirname, '../..', 'foo.bar'));

path.join() will handle leading/trailing slashes for you and just do the right thing and you don't have to try to remember when trailing slashes exist and when they dont.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow