我想将我的logServiceClient对象传递给server.js文件中包含的所有其他模块。当我运行以下代码时,它会打印出空对象;
logServiceClient{}
是否可以将logServiceClient传递给所有其他包含的模块?
server.js文件;
....
const logger = new Logger({
level: new CLevel('warn'),
ordered
})
var logServiceClient = require('./app/logServiceClient')(logger)
var userHandler = require('./app/userHandler')(logServiceClient)
userHandler文件;
module.exports = function(logServiceClient){
console.log('logServiceClient' + JSON.stringify(logServiceClient))
}
答案 0 :(得分:2)
有很多方法注入,而无需从其他模块中插入记录器。
function factoryCreateModule() {
var client = require('client')
client.$logger = require('logger')
}
function factoryRequireModule(module) {
var client = require(module)
client.$logger = require('logger')
}
var client = factoryCreateModule()
client.logger.log('hello')
var client2 = factoryRequireModule('client')
client2.logger.log('hello')
您当然可以缩小目标对象的范围...
var logger = {
log(message) {
console.log(message)
},
warn(message) {
console.log('!!! ' + message)
}
}
Object.prototype.$logger = logger
var x = 12;
x.$logger.log('I am a number')
var str = "Hello"
str.$logger.warn('WARNING FROM STRING')
global是模块系统中的“窗口”。
// just for snippit to run
window.global = {}
var logger = {
log(message) {
console.log(message)
}
}
// main module
global.$logger = logger
// client module
global.$logger.log('hello world')
var logger = require('logger')
var client = require('client')(logger)
var client2 = require('client2')({logger})
var client3 = require('client3')
client3.init(logger)
答案 1 :(得分:1)
// file1.js
var foo = "bar";
exports.foo = foo;
// file2.js
var myModule = require('./file1');
var foo = myModule.foo;