如何从Node.js中的不同应用程序注入模块

9 javascript amd node.js express microservices

我有两个一起运行的节点应用程序/服务,1.主应用程序2.第二个应用程序

主应用程序负责显示最终不同应用程序的所有数据.现在我在主应用程序中放置了第二个应用程序的一些代码,现在它正在工作,但我希望它能够解耦.我的意思是secnod应用程序的代码不会在主应用程序中(通过某种方式在运行时注入它)

就像第二个服务注册到主应用程序注入它的代码.它的代码只是两个模块,是否可以在nodejs中完成?

const Socket = require('socket.io-client');
const client = require("./config.json");

module.exports =  (serviceRegistry, wsSocket) =>{
    var ws = null;
    var consumer = () => {
        var registration = serviceRegistry.get("tweets");
        console.log("Service: " + registration);
        //Check if service is online
        if (registration === null) {
            if (ws != null) {
                ws.close();
                ws = null;
                console.log("Closed websocket");
            }
            return
        }
        var clientName = `ws://localhost:${registration.port}/`
        if (client.hosted) {
            clientName = `ws://${client.client}/`;
        }
        //Create a websocket to communicate with the client
        if (ws == null) {
            console.log("Created");
            ws = Socket(clientName, {
                reconnect: false
            });
            ws.on('connect', () => {
                console.log("second service is connected");
            });
            ws.on('tweet', function (data) {
                wsSocket.emit('tweet', data);
            });
            ws.on('disconnect', () => {
                console.log("Disconnected from blog-twitter")
            });
            ws.on('error', (err) => {
                console.log("Error connecting socket: " + err);
            });
        }
    }
    //Check service availability
    setInterval(consumer, 20 * 1000);
}
Run Code Online (Sandbox Code Playgroud)

在主模块中我放了这个代码,我想通过在运行时以某种方式注入它来解耦它?例子将非常有帮助......

man*_*shg 4

您将必须使用vm模块来实现此目的。更多技术信息请参见https://nodejs.org/api/vm.html。让我解释一下如何使用它:

  1. 您可以使用 APIvm.script从您想要稍后运行的代码创建编译后的 js 代码。看官方文档的描述

创建新的 vm.Script 对象会编译代码,但不会运行它。编译后的vm.Script可以稍后多次运行。需要注意的是,代码并未绑定到任何全局对象;相反,它在每次运行之前绑定,仅针对该运行。

  1. 现在,当您想要插入或运行此代码时,您可以使用script.runInContextAPI。

他们的官方文档中的另一个很好的例子:

'use strict';
const vm = require('vm');

let code =
`(function(require) {

   const http = require('http');

   http.createServer( (request, response) => {
     response.writeHead(200, {'Content-Type': 'text/plain'});
     response.end('Hello World\\n');
   }).listen(8124);

   console.log('Server running at http://127.0.0.1:8124/');
 })`;

 vm.runInThisContext(code)(require);
Run Code Online (Sandbox Code Playgroud)

另一个直接使用js文件的例子:

var app = fs.readFileSync(__dirname + '/' + 'app.js');
vm.runInThisContext(app);
Run Code Online (Sandbox Code Playgroud)

您可以将此方法用于要插入的条件代码。