从node.js模块访问全局variables?
我想将一些函数分解成一个名为helpers.js
的文件,其中我已经把下面显示的代码。 我应该怎么做来访问我的方法内的app
variables,以便能够获取我的configuration元素名为Path
?
Helpers = { fs: require('fs'), loadFileAsString: function(file) { return this.fs.readFileSync( app.set('Path') + file)+ ''; } } module.exports = Helpers;
所以从我看到你需要app
variables表格Express。 你可以把它作为一个函数参数发送到loadFileAsString,例如:
helpers.js
Helpers = { ... loadFileAsString: function(file, app) { return this.fs.readFileSync( app.set('Path') + file)+ ''; } } module.exports = Helpers;
some_file.js
app = express.createServer(); ... helpers = require('./helpers.js'); helpers.loadfileAsString(file, app);
如果你希望应用程序是全局的,你也可以这样做: global.app = app
,你可以在任何地方访问应用程序,而不必把它作为函数参数发送。