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

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

提交回复
热议问题