【问题标题】:Use global module in node在节点中使用全局模块
【发布时间】:2018-03-29 22:56:25
【问题描述】:

我有一个带有一些模块的节点应用程序。
我想以这种方式使用我的模块之一:

  • 在 server.js 中初始化模块(从 npm 调用的第一个文件)
  • 从套接字传递请求时,在我的模块中设置请求配置
  • 将该模块与其他模块中的请求配置一起使用。

例子:

模块.js

'use strict';

const Module = require('module');

let module = new Module({
    some_information
});

function test(message) {
    module.info(message);
}

function configureRequest(request) {
    module.configure({
        payload: {
            request: request
        }
    });
}

module.exports = {
    info,
    configureRequest
};

server.js(一小段代码)

let module = require('./src/module.js');

get_request.js

let module = require('./src/logger.js');
let another = require('./src/another.js');

scServer.on('connection', function (socket) {
     module.configureRequest(socket.request);
     module.info('test'); //inside it there is request 
     another.start();
});

另一个.js

let module = require('./src/logger.js');   
module.info('test'); //inside it there isn't request 

正如您在 another.js 中看到的那样,我再次需要我的全局模块,因此未设置请求,我不希望每次请求都可以传递到所有模块(我有很多模块使用全局模块)

我该如何解决?

【问题讨论】:

标签: node.js


【解决方案1】:

我通常做的是使用 consign 模块在我的应用程序中自动加载我的模块。 https://github.com/jarradseers/consign

【讨论】:

  • 我更喜欢不使用这样的解决方案,并了解如何制作全局模块或如何在模块之间共享它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多