如何使用NodeJS将变量传递给其他模块?

时间:2018-07-25 10:55:13

标签: javascript node.js

我想将我的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))
}

2 个答案:

答案 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')

将记录器传递到构造函数或init方法中

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;