Javascript Node.js 不能在同一目录中要求 .js 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26311577/
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
Node.js cannot require a .js file in the same directory
提问by Antrikshy
I have a node-webkit project with a main.js. At the very top, I have
我有一个带有main.js. 在最顶端,我有
var updater = require("./updater.js");
and I have a file named updater.jsin the same directory as main.js. When I run the app, I get the error
我有一个updater.js与main.js. 当我运行应用程序时,我收到错误
Uncaught Error: Cannot find module './updater.js'
updater.jshas one line in it:
updater.js其中有一行:
module.exports = "Hello!";
I have no idea why it cannot require the file. I have seen another project do the same thing. I can requireregular npmmodules just fine from the same main.js.
我不知道为什么它不能要求该文件。我见过另一个项目做同样的事情。我可以require定期npm模块刚刚从同一罚款main.js。
回答by Dmitry Matveev
This is because, when you run you app (main.js) using node-webkit the root (working) directory is where the index.html is in, so './' refers to that directory not the one in which the file you requesting the module from is in.
这是因为,当您使用 node-webkit 运行您的应用程序 (main.js) 时,根(工作)目录是 index.html 所在的位置,因此“./”指的是该目录,而不是您所在文件所在的目录请求模块来自。
You can easily solve this problem by using resolve method in 'path' node moduleand provide the output from it to the require method in your working file
您可以通过使用“路径”节点模块中的解析方法轻松解决此问题,并将其输出提供给工作文件中的 require 方法
Simply do the following:
只需执行以下操作:
var path = require('path');
var updater = require( path.resolve( __dirname, "./updater.js" ) );
EDIT : info on global node object '__dirname' (and others) can by found here.

