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

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

    create two files e.g standard_funcs.js and main.js

    1.) standard_funcs.js

    // Declaration --------------------------------------
    
     module.exports =
       {
         add,
         subtract
         // ...
       }
    
    
    // Implementation ----------------------------------
    
     function add(x, y)
     {
       return x + y;
     }
    
     function subtract(x, y)
     {
       return x - y;
     }
        
    
    // ...
    

    2.) main.js

    // include ---------------------------------------
    
    const sf= require("./standard_funcs.js")
    
    // use -------------------------------------------
    
    var x = sf.add(4,2);
    console.log(x);
    
    var y = sf.subtract(4,2);
    console.log(y);
    
        
    

    output

    6
    2
    

提交回复
热议问题