我怎么写这个回到父2层去找文件?

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

当前回答

这很好

path.join(__dirname + '/../client/index.html')
const path = require('path')
const fs = require('fs')
    fs.readFile(path.join(__dirname + '/../client/index.html'))

其他回答

使用路径。加入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()将为你处理开头/结尾斜杠,只是做正确的事情,你不必试图记住什么时候结尾斜杠存在,什么时候不存在。

试试这个:

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

请注意相对路径开头的正斜杠。

看起来你需要路径模块。(路径。特别是正常化)

var path = require("path"),
    fs = require("fs");

fs.readFile(path.normalize(__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。resolve()获取父文件夹

父1级:路径。解析(__dirname, '..') + '/'

父2级:路径。解决(__dirname”. .', '..') + '/'