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’);
fs.readFile(__dirname + '/../../foo.bar');
Note the forward slash at the beginning of the relative path.
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.
I know it is a bit picky, but all the answers so far are not quite right.
The point of path.join() is to eliminate the need for the caller to know which directory separator to use (making code platform agnostic).
Technically the correct answer would be something like:
var path = require("path"); fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));
I would have added this as a comment to Alex Wayne’s answer but not enough rep yet!
EDIT: as per user1767586’s observation
The easiest way would be to use
path.resolve(__dirname, '..', '..');
var path = require("path"), fs = require("fs"); fs.readFile(path.normalize(__dirname + "/../../foo.bar"));
If another module calls yours and you’d still like to know the location of the main file being run you can use a modification of @Jason’s code:
var path = require('path'), __parentDir = path.dirname(process.mainModule.filename); fs.readFile(__parentDir + '/foo.bar');
That way you’ll get the location of the script actually being run.