Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of !module.parent in nodejs

Tags:

node.js

Can you please explain why we are using !module.parent in node. why Node.js Accessing parent modules

if (!module.parent) {
  app.listen(3000);
  console.log('listening on port 3000');
}
like image 565
Dileep Kheni Avatar asked Dec 25 '13 06:12

Dileep Kheni


People also ask

What is module parent?

The "parent" is the module that caused the script to be interpreted (and cached), if any: // $ node foo.js console. log(module. parent); // `null` // require('./foo') console.

Why do we use Node modules?

You can think of the node_modules folder like a cache for the external modules that your project depends upon. When you npm install them, they are downloaded from the web and copied into the node_modules folder and Node. js is trained to look for them there when you import them (without a specific path).

What are CommonJS modules?

CommonJS modules are the original way to package JavaScript code for Node.js. Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes. In Node.js, each file is treated as a separate module.

What is module exports used for?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.


2 Answers

I Found answer. You can use module.parent to determine if the current script is loaded by another script. Example is here :

a.js:

if (!module.parent) {
    console.log("I'm parent");
} else {
    console.log("I'm child");
}

b.js:

require('./a')

run node a.js will output:

I'm parent

run node b.js will output:

I'm child
like image 137
Dileep Kheni Avatar answered Oct 16 '22 14:10

Dileep Kheni


In hierarchical programming paradigms many tasks are done at higher level of hierarchy of a framework, it provides better performance and efficiency. Same is being applied here. If the parent object of running module is not listening to any port, then this task is done by its child object explicitly.

like image 35
Khatana Avatar answered Oct 16 '22 14:10

Khatana