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

后端 未结 25 2527
猫巷女王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.

    0 讨论(0)
  • 2020-11-22 04:58

    To turn "tools" into a module, I don't see hard at all. Despite all the other answers I would still recommend use of module.exports:

    //util.js
    module.exports = {
       myFunction: function () {
       // your logic in here
       let message = "I am message from myFunction";
       return message; 
      }
    }
    

    Now we need to assign this exports to global scope (in your app|index|server.js )

    var util = require('./util');
    

    Now you can refer and call function as:

    //util.myFunction();
    console.log(util.myFunction()); // prints in console :I am message from myFunction 
    
    0 讨论(0)
  • 2020-11-22 05:00

    You can simple just require('./filename').

    Eg.

    // file: index.js
    var express = require('express');
    var app = express();
    var child = require('./child');
    app.use('/child', child);
    app.get('/', function (req, res) {
      res.send('parent');
    });
    app.listen(process.env.PORT, function () {
      console.log('Example app listening on port '+process.env.PORT+'!');
    });
    
    // file: child.js
    var express = require('express'),
    child = express.Router();
    console.log('child');
    child.get('/child', function(req, res){
      res.send('Child2');
    });
    child.get('/', function(req, res){
      res.send('Child');
    });
    
    module.exports = child;
    

    Please note that:

    1. you can't listen PORT on the child file, only parent express module has PORT listener
    2. Child is using 'Router', not parent Express moudle.
    0 讨论(0)
  • 2020-11-22 05:01

    say we wants to call function ping() and add(30,20) which is in lib.js file from main.js

    main.js

    lib = require("./lib.js")
    
    output = lib.ping();
    console.log(output);
    
    //Passing Parameters
    console.log("Sum of A and B = " + lib.add(20,30))
    

    lib.js

    this.ping=function ()
    {
        return  "Ping Success"
    }
    
    //Functions with parameters
    this.add=function(a,b)
        {
            return a+b
        }
    
    0 讨论(0)
  • 2020-11-22 05:01

    I was as well searching for an option to include code without writing modules, resp. use the same tested standalone sources from a different project for a Node.js service - and jmparattes answer did it for me.

    The benefit is, you don't pollute the namespace, I don't have trouble with "use strict"; and it works well.

    Here a full sample:

    Script to load - /lib/foo.js

    "use strict";
    
    (function(){
    
        var Foo = function(e){
            this.foo = e;
        }
    
        Foo.prototype.x = 1;
    
        return Foo;
    
    }())
    

    SampleModule - index.js

    "use strict";
    
    const fs = require('fs');
    const path = require('path');
    
    var SampleModule = module.exports = {
    
        instAFoo: function(){
            var Foo = eval.apply(
                this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
            );
            var instance = new Foo('bar');
            console.log(instance.foo); // 'bar'
            console.log(instance.x); // '1'
        }
    
    }
    

    Hope this was helpfull somehow.

    0 讨论(0)
  • 2020-11-22 05:01

    Use:

    var mymodule = require("./tools.js")
    

    app.js:

    module.exports.<your function> = function () {
        <what should the function do>
    }
    
    0 讨论(0)
提交回复
热议问题