Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
Alexander Mills Avatar asked Jan 17 '15 06:01

Alexander Mills


People also ask

How do I stop a node script from running?

Method 1: Using ctrl+C key: When running a program of NodeJS in the console, you can close it with ctrl+C directly from the console with changing the code shown below: Method 2: Using process. exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code.

Why NodeJS code so quick even though it is written in?

The virtual machine can take the source code to compile it into the machine code at runtime. What it means is that all the “hot” functions that get called often than not can be compiled to the machine code thus boosting the execution speed.

Why require is not working in js?

This usually happens because your JavaScript environment doesn't understand how to handle the call to require() function you defined in your code. Here are some known causes for this error: Using require() in a browser without RequireJS. Using require() in Node.

Can I use import in node instead of require?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.


2 Answers

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();
like image 175
Anurag Peshne Avatar answered Nov 07 '22 03:11

Anurag Peshne


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.

like image 44
Yuri Zarubin Avatar answered Nov 07 '22 02:11

Yuri Zarubin