fs.readFileSync 不是文件相关的吗?节点.js [英] fs.readFileSync is not file relative? Node.js

查看:50
本文介绍了fs.readFileSync 不是文件相关的吗?节点.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

If I now run node ./tests/test.js from 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.

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

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 中重写路径?

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

推荐答案

您可以使用 path.resolve:

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

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

这篇关于fs.readFileSync 不是文件相关的吗?节点.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆