Node.js – res.sendFile – 错误:ENOENT,stat – 即使path是正确的
这是我的文件夹结构:
- 根文件夹
- …
- …
- …
- app.js
- escape_iframe.html
- …
从app.js
内我正在做:
res.sendFile('escape_iframe.html' , {root : __dirname});
和我得到的错误是:
Error: ENOENT, stat '/app/escape_iframe.html'
我想这是一个可怕的方式说,该文件不能在所提供的path中find?
无论如何,正如你可以告诉我只是想提供一个文件,这是一个app.js
的sibling
(这是res.sendFile(...
调用正在作出的文件格式)
我也试过: res.sendFile('escape_iframe.html');
我得到: path must be absolute or specify root to res.sendFile
我究竟做错了什么 ?
指定的path.
是相对于当前的工作目录,而不是相对于脚本文件。 所以,如果你运行节点app.js,可能会find该文件,但如果运行节点文件夹/ app.js,则不会。
要创build相对于脚本的path,必须使用__dirname
variables。
res.sendFile(__dirname + '/path/to/escape_iframe.html');
指定的path.
是相对于path的,任何数量的正斜杠都被截断为单斜杠。 当进程node filename.js
无法find文件名时,可能会出现此错误。 https://nodejs.org/api/errors.html#errors_enoent_no_such_file_or_directory
我的build议是:
var path = require('path') //process.cwd() returns the current directory of the project res.sendFile(process.cwd(),'/path/to/escape_iframe.html');