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

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

    If, despite all the other answers, you still want to traditionally include a file in a node.js source file, you can use this:

    var fs = require('fs');
    
    // file is included here:
    eval(fs.readFileSync('tools.js')+'');
    
    • The empty string concatenation +'' is necessary to get the file content as a string and not an object (you can also use .toString() if you prefer).
    • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

    Please note that in most cases this is bad practice and you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.

    Update 2015-08-06

    Please also note this won't work with "use strict"; (when you are in "strict mode") because functions and variables defined in the "imported" file can't be accessed by the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoid the solution described here.

提交回复
热议问题