NodeJs require('./file.js') 问题

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

NodeJs require('./file.js') issues

node.jsrequire

提问by Patrick Lorio

I am having issues including files to execute in my NodeJs project.

我遇到了问题,包括要在我的 NodeJs 项目中执行的文件。

I have two files in the same directory:

我在同一个目录中有两个文件:

a.js

js

var test = "Hello World";

and

b.js

js

require('./a.js');
console.log(test);

I execute b.js with node b.jsand get the error ReferenceError: test is not defined.

我执行 b.jsnode b.js并得到错误ReferenceError: test is not defined

I have looked through the docs http://nodejs.org/api/modules.html#modules_file_modules

我浏览了文档http://nodejs.org/api/modules.html#modules_file_modules

What am I missing? Thanks in advance.

我错过了什么?提前致谢。

回答by rdrey

Change a.jsto export the variable:

更改a.js以导出变量:

exports.test = "Hello World";

and assign the return value of require('./a.js')to a variable:

并将 的返回值赋给require('./a.js')一个变量:

var a = require('./a.js');
console.log(a.test);

Another pattern you will often see and probably use is to assign something (an object, function) to the module.exportsobject in a.js, like so:

您经常会看到并可能使用的另一种模式是module.exportsa.js 中为对象分配一些东西(对象、函数),如下所示:

module.exports = { big: "string" };

回答by Andrew T Finnell

You are misunderstanding what should be happening. The variables defined in your module are not shared. NodeJS scopes them.

你误解了应该发生的事情。模块中定义的变量不共享。NodeJS 限定它们的范围。

You have to return it with module.exports.

你必须用 返回它module.exports

a.js

js

module.exports = "Hello World";

b.js

js

var test = require('./a.js');
console.log(test);

回答by philipzhao

if you want to export the variable in another file.There are two patterns. One is a.js
global.test = "Hello World";//test here is global variable,but it will be polluted

如果要将变量导出到另一个文件中。有两种模式。一个是a.js
global.test = "Hello World";//test这里是全局变量,但是会被污染

The other is
a.js module.exports.test = "Hello World";or exports.test= "Hello World"; b.js var test = require('./a.js');//test in b.js can get the test in a.js console.log(test);

另一个是
a.jsmodule.exports.test = "Hello World";或exports.test ="Hello World"; b.js //b.js var test = require('./a.js');中的test可以得到a.js中的test console.log(test);