本文介绍了如何在node.js中使用全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我要使用自定义记录器:
For example I want to use custom logger:
logger = require('basic-logger'),
logger.setLevel('info')
var customConfig = {
showMillis: true,
showTimestamp: true
}
var log = new logger(customConfig)
如何在其他模块而不是console.log中使用此记录器?
How to use this logger in other modules instead of console.log ?
推荐答案
大多数人建议不要使用全局变量.如果要在不同模块中使用相同的记录器类,则可以这样做
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
logger.js
module.exports = new logger(customConfig);
foobar.js
foobar.js
var logger = require('./logger');
logger('barfoo');
如果您想要全局变量,可以执行以下操作:
If you do want a global variable you can do:
global.logger = new logger(customConfig);
这篇关于如何在node.js中使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!