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

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

    I just want to add, in case you need just certain functions imported from your tools.js, then you can use a destructuring assignment which is supported in node.js since version 6.4 - see node.green.


    Example: (both files are in the same folder)

    tools.js

    module.exports = {
        sum: function(a,b) {
            return a + b;
        },
        isEven: function(a) {
            return a % 2 == 0;
        }
    };
    

    main.js

    const { isEven } = require('./tools.js');
    
    console.log(isEven(10));
    

    output: true


    This also avoids that you assign those functions as properties of another object as its the case in the following (common) assignment:

    const tools = require('./tools.js');

    where you need to call tools.isEven(10).


    NOTE:

    Don't forget to prefix your file name with the correct path - even if both files are in the same folder, you need to prefix with ./

    From Node.js docs:

    Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

提交回复
热议问题