fs: how do I locate a parent folder?

2019-01-16 09:13发布

问题:

How do I write this to go back up the parent 2 levels to find a file?

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

回答1:

Try this:

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

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



回答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.



回答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!

EDIT: as per user1767586's observation



回答4:

The easiest way would be to use path.resolve:

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


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


回答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.



回答7:

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


回答8:

You can use

path.join(__dirname, '../..');


回答9:

this will also work:

fs.readFile(`${__dirname}/../../foo.bar`);