Alexander Mills Alexander Mills - 1 month ago 8
Node.js Question

Node.js requiring a script but not running it

In Node.js, when you do

var otherscript = require('otherscript');


it runs the script upon the require

I am wondering if there is a way to "require" a script without running it, so that you can run it later when you want to.

Is there any good reason why not?

Answer

If you can edit the 'otherscript' (no one else is using that script) then you can simply enclose the whole code inside a function and add it to exports. Example:

otherscript:

module.exports = function(){
  //original code goes here
};

Then use as:

var otherscript = require('otherscript');
var obj = otherscript();