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

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

    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);
    

提交回复
热议问题