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

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

    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 
    

提交回复
热议问题