node.js - 不适用于 Node js 中的 fs.readFile

标签 node.js file fs

我有:

 fs.readFile('../services/Prescipcion.xml', "utf8", function (err, data) {
    console.log("err->", err);
    console.log("data", data);
 });

它会记录:

err-> { 
  [Error: ENOENT: no such file or directory, open '../services/Prescipcion.xml']
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '../services/Prescipcion.xml' 
}

我不明白为什么会这样。

最佳答案

错误信息是no such file or directory,所以乍一看这很可能意味着文件的路径不正确。

文件名不正确(错字?)或目录解析不正确。请注意,将针对 process.cwd() 解析相对路径:

process.cwd(): Returns the current working directory of the process.

您可以尝试使用 console.log(process.cwd()) 来帮助您调试问题。

如果文件 Prescipcion.xml 应该从运行脚本的地方本地检索,您还可以使用以下构造:

fs.readFileSync(path.join(__dirname, '../services') + '/Prescipcion.xml', 'utf8');

__dirname: The name of the directory that the currently executing script resides in.

关于node.js - 不适用于 Node js 中的 fs.readFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33342984/

相关文章:

node.js - BotFrameworkAdapter 缺少事件类型 - 本地调试 Messenger

javascript - 如何将 snekfetch 结果放入对象中?

c++ - 一次输入一行到c++中的字符串数组

android - java.lang.ClassCastException : java. io.File 无法转换为 android.os.Parcelable

java - 如何从包含多种数据类型的文本文件中进行输入

node.js - 确定 Node js中读取流的长度

node.js - 异步和递归目录扫描,用于 Nodejs 和 Expressjs 中的文件列表

node.js - 为什么 Express.js 的 app.get() 只能在调用 app.listen() 的同一个文件中工作?

javascript - 解析 "... has no method ' 替换时 JSON 错误'"

node.js - 针对 Heroku 和 node.js 上的每个请求运行的后台作业