Alexander Mills Alexander Mills - 1 year ago 99
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 Source

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:


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

Then use as:

var otherscript = require('otherscript');
var obj = otherscript();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download