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

这是我的第一个文件:

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

我想在另一个文件中的这个configurationvariables,所以我在另一个文件中做的是:

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

但它给了我一个错误。

 TypeError: Cannot read property 'confvar' of undefined 

请build议我能做些什么?

你需要的是module.exports

出口

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

例如,如果你想在sourceFile.js暴露variableName值为"variableValue" ,那么你可以设置整个导出为:

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

或者你可以设置个人价值:

 module.exports.variableName = "variableValue"; 

要在另一个文件中使用这个值,你需要首先require(...) (相对path):

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