Node.js 在节点中使用全局模块
我有一个带有一些模块的节点应用程序。Node.js 在节点中使用全局模块,node.js,Node.js,我有一个带有一些模块的节点应用程序。 我想以这种方式使用我的一个模块: 初始化server.js中的模块(从npm调用的第一个文件) 从套接字传递请求时,请在模块内设置请求配置 将该模块与其他模块中的请求配置一起使用 例如: module.js 'use strict'; const Module = require('module'); let module = new Module({ some_information }); function test(message)
我想以这种方式使用我的一个模块:
- 初始化server.js中的模块(从npm调用的第一个文件)
- 从套接字传递请求时,请在模块内设置请求配置
- 将该模块与其他模块中的请求配置一起使用
'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(一小段代码)
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
正如您在另一个.js中看到的,我再次需要我的全局模块,因此请求没有设置,我不希望每次请求都能传递到所有模块中(我有很多很多使用全局模块的模块)
我该如何解决呢?我通常使用委托模块在我的应用程序中自动加载我的模块 我不希望使用这样的解决方案,而是希望了解如何创建全局模块或如何在模块之间共享该模块。该链接显示了如何正确地为Node.js创建全局模块
let module = require('./src/logger.js');
module.info('test'); //inside it there isn't request