Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fs: how do I locate a parent folder?

People also ask

Where is the parent folder?

A folder that is one level up from the current directory in a file hierarchy. In a DOS, Windows or Mac command line, two dots (..) refer to the preceding folder/directory level.

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

How do I navigate to a parent directory?

There is no way to go to the parent folder right out of the search results, as that is not how it operates, however if you double-click on the quick launch search result, resulting in navigating to the folder, then press alt+up then it will go to the parent folder.

What is the parent directory of a file?

With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.


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, '..', '..');