I was looking in the node.js module documentation, and noticed that each module has a property- module.parent
. I tried to use it, but got burnt by the module caching- module.parent
only ever seems to the module that first require()'d it, irrespective of current context.
So what is the usage of it? Is there any other way for me to get a reference to the current require()ing module? Right now I'm wrapping the module in a function, so that it is called like:
require("mylibrary")(module)
but that seems sub-optimal.
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
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.
7. Which function is used to include modules in Node Js. require();
In Node. js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiples files/folders.
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.log(module.parent); // `{ ... }`
What you're expecting is the "caller," which Node doesn't retain for you. For that, you'll need the exported function you're currently using to be a closure for the value.
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