In Node.js, how do I “include” functions from my other files?

后端 未结 25 2889
猫巷女王i
猫巷女王i 2020-11-22 04:22

Let\'s say I have a file called app.js. Pretty simple:

var express = require(\'express\');
var app = express.createServer();
app.set(\'views\', __dirname + \         


        
25条回答
  •  耶瑟儿~
    2020-11-22 04:58

    If you'd like to take advantage of multiple CPUs & Microservice architecture, to speed things up...Use RPCs over forked processes.

    Sounds complex, but it's simple if you use octopus.

    Here's an example:

    on tools.js add :

    const octopus = require('octopus');
    var rpc = new octopus('tools:tool1');
    
    rpc.over(process, 'processRemote');
    
    var sum = rpc.command('sum'); // This is the example tool.js function to make available in app.js
    
    sum.provide(function (data) { // This is the function body
        return data.a + data.b;
    });
    

    on app.js, add :

    const { fork } = require('child_process');
    const octopus = require('octopus');
    const toolprocess = fork('tools.js');
    
    var rpc = new octopus('parent:parent1');
    rpc.over(toolprocess, 'processRemote');
    
    var sum = rpc.command('sum');
    
    // Calling the tool.js sum function from app.js
    sum.call('tools:*', {
        a:2, 
        b:3
    })
    .then((res)=>console.log('response : ',rpc.parseResponses(res)[0].response));
    

    disclosure - I am the author of octopus, and built if for a similar usecase of mine, since i couldn't find any lightweight libraries.

提交回复
热议问题