While the answer posted by JohnKiller is technically correct, I would like to point out a solution that uses vm.runInContext and is more reliable in my opinion.
// app.js var fs = require('fs'); module.exports = function onRequest(req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); } // server.js var appFile = __dirname + '/' + 'app.js'; var app = fs.readFileSync(appFile); var context = vm.createContext({ __filename: appFile, __dirname: __dirname, require: require, module: { exports: {} } }); context.exports = context.module.exports; vm.runInContext(app, context, { filename: appFile }); var onRequest = context.module.exports; var http = require('http'); var server = http.createServer(onRequest); server.listen(8080, '127.0.0.1');
I see the following main advantages:
1) The global context is not polluted by additional variables used only by the downloaded script file.
2) The code downloaded from the external file is isolated, it cannot directly change the variables of the calling area of the caller. It is very clear which variables are available for the external file.
3) The code in the external file is encapsulated itself and does not depend on any external modules provided in the context. In fact, this is a regular Node.js file that can be downloaded directly via require('./app.js')
source share