如何从node.js中的文件到另一个文件获取变量

时间:2021-12-16 16:02:38

Here is my first file:

这是我的第一个文件:

var self=this;
var config ={
    'confvar':'configval'
};

I want this config variable in another file, so what I have done in another file is:

我想在另一个文件中使用这个配置变量,所以我在另一个文件中做的是:

conf = require('./conf');
    url=conf.config.confvar;

but it gives me an error.

但它给了我一个错误。

TypeError: Cannot read property 'confvar' of undefined

Please suggest what can i do?

请建议我该怎么办?

1 个解决方案

#1


58  

What you need is module.exports

你需要的是module.exports

Exports

出口

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

在当前模块的所有实例之间共享的对象,可通过require()访问。 exports与module.exports对象相同。有关更多信息,请参阅src / node.js。出口实际上并不是全球性的,而是每个模块的本地化。

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

例如,如果您想在sourceFile.js上使用值“variableValue”公开variableName,那么您可以设置整个导出:

module.exports = { variableName: "variableValue" };

OR you can set the individual value with:

或者您可以使用以下方式设置单个值:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

要在另一个文件中使用该值,您需要首先要求(...)(使用相对路径):

var sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

#1


58  

What you need is module.exports

你需要的是module.exports

Exports

出口

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

在当前模块的所有实例之间共享的对象,可通过require()访问。 exports与module.exports对象相同。有关更多信息,请参阅src / node.js。出口实际上并不是全球性的,而是每个模块的本地化。

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

例如,如果您想在sourceFile.js上使用值“variableValue”公开variableName,那么您可以设置整个导出:

module.exports = { variableName: "variableValue" };

OR you can set the individual value with:

或者您可以使用以下方式设置单个值:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

要在另一个文件中使用该值,您需要首先要求(...)(使用相对路径):

var sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);