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');
}
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.
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).
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With