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

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

    Here is a plain and simple explanation:

    Server.js content:

    // Include the public functions from 'helpers.js'
    var helpers = require('./helpers');
    
    // Let's assume this is the data which comes from the database or somewhere else
    var databaseName = 'Walter';
    var databaseSurname = 'Heisenberg';
    
    // Use the function from 'helpers.js' in the main file, which is server.js
    var fullname = helpers.concatenateNames(databaseName, databaseSurname);
    

    Helpers.js content:

    // 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
    module.exports = 
    {
      // This is the function which will be called in the main file, which is server.js
      // The parameters 'name' and 'surname' will be provided inside the function
      // when the function is called in the main file.
      // Example: concatenameNames('John,'Doe');
      concatenateNames: function (name, surname) 
      {
         var wholeName = name + " " + surname;
    
         return wholeName;
      },
    
      sampleFunctionTwo: function () 
      {
    
      }
    };
    
    // Private variables and functions which will not be accessible outside this file
    var privateFunction = function () 
    {
    };
    

提交回复
热议问题