node.js fs.readFileSync 不是文件相关的吗?节点.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44600943/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:17:50  来源:igfitidea点击:

fs.readFileSync is Not File Relative? Node.js

node.js

提问by Arman

-Suppose I have a file in the root of my project called "file.xml"

- 假设我的项目根目录中有一个名为“file.xml”的文件

-Suppose I have a test file in tests/ called "test.js" and it has

- 假设我在 tests/ 中有一个名为“test.js”的测试文件,它有

const file = fs.readFileSync("../file.xml");

If I now run node ./tests/test.jsfrom the root of my project it says ../file.xml does not exist. If I run the same command from within the tests directory, then it works.

如果我现在node ./tests/test.js从我的项目的根目录运行,它会说 ../file.xml 不存在。如果我从测试目录中运行相同的命令,那么它就可以工作。

It seems fs.readFileSync is relative to the directory where the script is invoked from, instead of where the script actually is. If I wrote fs.readFileSync("./file.xml")in test.js it would look more confusing and is not consistent with relative paths in a require statement which are file relative.

似乎 fs.readFileSync 与调用脚本的目录有关,而不是脚本实际所在的目录。如果我fs.readFileSync("./file.xml")在 test.js 中编写它会看起来更混乱,并且与文件相关的 require 语句中的相对路径不一致。

Why is this?

为什么是这样?

How can I avoid having to rewrite the paths in my fs.readFileSync?

如何避免在 fs.readFileSync 中重写路径?

回答by cartant

You can resolve the path relative the location of the source file - rather than the current directory - using path.resolve:

您可以解析相对于源文件位置的路径 - 而不是当前目录 - 使用path.resolve

const path = require("path");
const file = fs.readFileSync(path.resolve(__dirname, "../file.xml"));