Node.js,无法打开文件。错误:ENOENT,统计 './path/to/file'

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

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

node.jsexpress

提问by loganfsmyth

I have developed a node.js program using the express framework on my computer, where it runs fine with no complaints.

我在我的电脑上使用 express 框架开发了一个 node.js 程序,它运行良好,没有任何抱怨。

However, when I run the program on my SUSE Studio appliance, where it is intended to live, I receive an error at any file interaction.

但是,当我在 SUSE Studio 设备上运行该程序时,我会在任何文件交互中收到错误消息。

Error: ENOENT, stat './path/to/file'

I have checked that the file permissions are correct, which they are. My computer and my appliance are running different versions of node, if this matters.

我已经检查过文件权限是否正确,它们是正确的。如果这很重要,我的计算机和我的设备正在运行不同版本的节点。

Any thoughts?

有什么想法吗?

回答by loganfsmyth

Paths specified with a .are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.jsbut not if you run node folder/app.js. The only exception to this is require('./file')and that is only possible because requireexists per-module and thus knows what module it is being called from.

用 a 指定的路径.是相对于当前工作目录的,而不是相对于脚本文件的。因此,如果您运行,可能会找到该文件,node app.js但如果您运行node folder/app.js. 唯一的例外是require('./file')并且那是唯一可能的,因为require每个模块都存在,因此知道它是从哪个模块调用的。

To make a path relative to the script, you must use the __dirnamevariable.

要创建相对于脚本的路径,您必须使用该__dirname变量。

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

或潜在地

path.join(__dirname, 'path', 'to', 'file')

回答by AmirtharajCVijay

Here the code to use your app.js

这里是使用你的 app.js 的代码

input specifies file name

输入指定文件名

res.download(__dirname+'/'+input);