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

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

    The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename

    Note that, as of today, there's a bug in the vm module that prevenst runInThisContext from doing the right when invoked from a new context. This only matters if your main program executes code within a new context and then that code calls runInThisContext. See https://github.com/joyent/node/issues/898

    Sadly, the with(global) approach that Fernando suggested doesn't work for named functions like "function foo() {}"

    In short, here's an include() function that works for me:

    function include(path) {
        var code = fs.readFileSync(path, 'utf-8');
        vm.runInThisContext(code, path);
    }
    

提交回复
热议问题