Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of module.parent in node.js? How can I refer to the require()ing module?

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.

like image 904
Alastair Avatar asked Nov 30 '12 19:11

Alastair


People also ask

For what require () is used in NodeJS?

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.

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.

Which function is used to include module in NodeJS?

7. Which function is used to include modules in Node Js. require();

What are NodeJS modules and what is their purpose what types of modules can be used in NodeJS?

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.


1 Answers

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.

like image 77
Jonathan Lonowski Avatar answered Sep 22 '22 03:09

Jonathan Lonowski