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

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

    Udo G. said:

    • 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).

    He's right, but there's a way to affect the global scope from a function. Improving his example:

    function include(file_) {
        with (global) {
            eval(fs.readFileSync(file_) + '');
        };
    };
    
    include('somefile_with_some_declarations.js');
    
    // the declarations are now accessible here.
    

    Hope, that helps.

提交回复
热议问题