我怎么写这个回到父2层去找文件?
fs.readFile(__dirname + 'foo.bar');
我怎么写这个回到父2层去找文件?
fs.readFile(__dirname + 'foo.bar');
当前回答
这也可以:
fs.readFile(`${__dirname}/../../foo.bar`);
其他回答
如果你不确定父结点在哪里,这个会给你路径;
var path = require('path'),
__parentDir = path.dirname(module.parent.filename);
fs.readFile(__parentDir + '/foo.bar');
你可以使用
path.join(__dirname, '../..');
试试这个:
fs.readFile(__dirname + '/../../foo.bar');
请注意相对路径开头的正斜杠。
你可以用不同的方法定位父文件夹下的文件,
const path = require('path');
const fs = require('fs');
// reads foo.bar file which is located in immediate parent folder.
fs.readFile(path.join(__dirname, '..', 'foo.bar');
// Method 1: reads foo.bar file which is located in 2 level back of the current folder.
path.join(__dirname, '..','..');
// Method 2: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(path.normalize(__dirname + "/../../foo.bar"));
// Method 3: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(__dirname + '/../../foo.bar');
// Method 4: reads foo.bar file which is located in 2 level back of the current folder.
fs.readFile(path.resolve(__dirname, '..', '..','foo.bar'));
我知道这有点挑剔,但到目前为止,所有的答案都不太正确。
path.join()的目的是消除调用者知道使用哪个目录分隔符的需要(使代码与平台无关)。
从技术上讲,正确答案应该是这样的:
var path = require("path");
fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));
我本想把这句话作为对Alex Wayne的回答的评论,但还不够代表!
编辑:根据用户1767586的观察