fs: how do I locate a parent folder?

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’);


Solution 1:

Try this:

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

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

Solution 2:

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.

Solution 3:

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!

Related:  Pass Javascript Array -> PHP

EDIT: as per user1767586’s observation

Solution 4:

The easiest way would be to use path.resolve:

path.resolve(__dirname, '..', '..');

Solution 5:

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"));

Solution 6:

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.