How do I write this to go back up the parent 2 levels to find a file?
fs.readFile(__dirname + 'foo.bar');
How do I write this to go back up the parent 2 levels to find a file?
fs.readFile(__dirname + 'foo.bar');
Try this:
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
:
path.resolve(__dirname, '..', '..');
Looks like you'll need the path
module. (path.normalize
in particular)
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.
If you not positive on where the parent is, this will get you the path;
var path = require('path'),
__parentDir = path.dirname(module.parent.filename);
fs.readFile(__parentDir + '/foo.bar');
You can use
path.join(__dirname, '../..');
this will also work:
fs.readFile(`${__dirname}/../../foo.bar`);