node.js NodeJS使用相对路径访问文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32705219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS accessing file with relative path
提问by lonelymo
It seemed like a straight forward problem. But I amn't able to crack this.
Within helper1.js I would like to access foobar.json (from config/dev/)
这似乎是一个直截了当的问题。但我无法破解这个。在 helper1.js 中,我想访问 foobar.json(来自config/dev/)
root
-config
--dev
---foobar.json
-helpers
--helper1.js
I couldn't get this to work fs: how do I locate a parent folder?
我无法让它工作fs:如何找到父文件夹?
Any help here would be great.
这里的任何帮助都会很棒。
回答by AerandiR
You can use the pathmodule to join the path of the directory in which helper1.jslives to the relative path of foobar.json. This will give you the absolute path to foobar.json.
您可以使用该path模块将所在目录的路径加入helper1.js到foobar.json. 这将为您提供到foobar.json.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
假设 UTF8 编码,这应该适用于 Linux、OSX 和 Windows。
回答by AdityaParab
Simple! The folder named ..is the parent folder, so you can make the path to the file you need as such
简单的!命名的文件夹..是父文件夹,因此您可以创建所需文件的路径
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../etc
如果你需要上升两个级别,你会写../../等
Some more details about this in this SO answerand it's comments
在这个 SO answer和它的评论中关于这个的更多细节

