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

后端 未结 25 2559
猫巷女王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 05:01

    I was as well searching for an option to include code without writing modules, resp. use the same tested standalone sources from a different project for a Node.js service - and jmparattes answer did it for me.

    The benefit is, you don't pollute the namespace, I don't have trouble with "use strict"; and it works well.

    Here a full sample:

    Script to load - /lib/foo.js

    "use strict";
    
    (function(){
    
        var Foo = function(e){
            this.foo = e;
        }
    
        Foo.prototype.x = 1;
    
        return Foo;
    
    }())
    

    SampleModule - index.js

    "use strict";
    
    const fs = require('fs');
    const path = require('path');
    
    var SampleModule = module.exports = {
    
        instAFoo: function(){
            var Foo = eval.apply(
                this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
            );
            var instance = new Foo('bar');
            console.log(instance.foo); // 'bar'
            console.log(instance.x); // '1'
        }
    
    }
    

    Hope this was helpfull somehow.

提交回复
热议问题