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

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

    You need no new functions nor new modules. You simply need to execute the module you're calling if you don't want to use namespace.

    in tools.js

    module.exports = function() { 
        this.sum = function(a,b) { return a+b };
        this.multiply = function(a,b) { return a*b };
        //etc
    }
    

    in app.js

    or in any other .js like myController.js :

    instead of

    var tools = require('tools.js') which force us to use a namespace and call tools like tools.sum(1,2);

    we can simply call

    require('tools.js')();
    

    and then

    sum(1,2);
    

    in my case I have a file with controllers ctrls.js

    module.exports = function() {
        this.Categories = require('categories.js');
    }
    

    and I can use Categories in every context as public class after require('ctrls.js')()

提交回复
热议问题