Alexander Mills
Alexander Mills

Reputation: 100000

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?

Upvotes: 8

Views: 3482

Answers (2)

Anurag Peshne
Anurag Peshne

Reputation: 1547

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();

Upvotes: 6

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

When you require a file or module, the return of that file/module is cached. In other words, it is really only executed once, and subsequent calls to require() of that file/module will only return a reference to the exact same object.

A common example of this is the Mongoose package, where calling require('mongoose') will return an instance of mongoose, on which you can call connect() to connect to the database. Calling require('mongoose') again in a different part of your program will return the same instance with the same database connection made available.

Upvotes: 2

Related Questions