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

后端 未结 25 3216
猫巷女王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:48

    Another way to do this in my opinion, is to execute everything in the lib file when you call require() function using (function(/* things here */){})(); doing this will make all these functions global scope, exactly like the eval() solution

    src/lib.js

    (function () {
        funcOne = function() {
                console.log('mlt funcOne here');
        }
    
        funcThree = function(firstName) {
                console.log(firstName, 'calls funcThree here');
        }
    
        name = "Mulatinho";
        myobject = {
                title: 'Node.JS is cool',
                funcFour: function() {
                        return console.log('internal funcFour() called here');
                }
        }
    })();
    

    And then in your main code you can call your functions by name like:

    main.js

    require('./src/lib')
    funcOne();
    funcThree('Alex');
    console.log(name);
    console.log(myobject);
    console.log(myobject.funcFour());
    

    Will make this output

    bash-3.2$ node -v
    v7.2.1
    bash-3.2$ node main.js 
    mlt funcOne here
    Alex calls funcThree here
    Mulatinho
    { title: 'Node.JS is cool', funcFour: [Function: funcFour] }
    internal funcFour() called here
    undefined
    

    Pay atention to the undefined when you call my object.funcFour(), it will be the same if you load with eval(). Hope it helps :)

提交回复
热议问题