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

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

    I was also looking for a NodeJS 'include' function and I checked the solution proposed by Udo G - see message https://stackoverflow.com/a/8744519/2979590. His code doesn't work with my included JS files. Finally I solved the problem like that:

    var fs = require("fs");
    
    function read(f) {
      return fs.readFileSync(f).toString();
    }
    function include(f) {
      eval.apply(global, [read(f)]);
    }
    
    include('somefile_with_some_declarations.js');
    

    Sure, that helps.

    0 讨论(0)
  • 2020-11-22 04:44

    Include file and run it in given (non-global) context

    fileToInclude.js

    define({
        "data": "XYZ"
    });
    

    main.js

    var fs = require("fs");
    var vm = require("vm");
    
    function include(path, context) {
        var code = fs.readFileSync(path, 'utf-8');
        vm.runInContext(code, vm.createContext(context));
    }
    
    
    // Include file
    
    var customContext = {
        "define": function (data) {
            console.log(data);
        }
    };
    include('./fileToInclude.js', customContext);
    
    0 讨论(0)
  • 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')()

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 04:48

    Another way to do this in my opinion, is to execute everything in the lib file when you call require() function using (function(/* things here */){})(); doing this will make all these functions global scope, exactly like the eval() solution

    src/lib.js

    (function () {
        funcOne = function() {
                console.log('mlt funcOne here');
        }
    
        funcThree = function(firstName) {
                console.log(firstName, 'calls funcThree here');
        }
    
        name = "Mulatinho";
        myobject = {
                title: 'Node.JS is cool',
                funcFour: function() {
                        return console.log('internal funcFour() called here');
                }
        }
    })();
    

    And then in your main code you can call your functions by name like:

    main.js

    require('./src/lib')
    funcOne();
    funcThree('Alex');
    console.log(name);
    console.log(myobject);
    console.log(myobject.funcFour());
    

    Will make this output

    bash-3.2$ node -v
    v7.2.1
    bash-3.2$ node main.js 
    mlt funcOne here
    Alex calls funcThree here
    Mulatinho
    { title: 'Node.JS is cool', funcFour: [Function: funcFour] }
    internal funcFour() called here
    undefined
    

    Pay atention to the undefined when you call my object.funcFour(), it will be the same if you load with eval(). Hope it helps :)

    0 讨论(0)
  • 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 () 
    {
    };
    
    0 讨论(0)
提交回复
热议问题