fs: how do I locate a parent folder? fs: how do I locate a parent folder? javascript javascript

fs: how do I locate a parent folder?


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