Search code examples
node.jsrequirewinston

How requiring a module on entry point makes available on other modules on NodeJS?


This is probably a duplicated question, but I couldn't find anything. Since I'm learning NodeJS, I think that I'm not using the right words to search, so it's hard to find an answer.

Here is the situation:

I'm currently following an online course about NodeJS and coding an API. In the current step we are using Winston library to log errors. The instructor, have configured on Index,js, which is the entry point of the app, like this:

File: index.js

const winston = require('winston');
const errorHandler = require(./middleware/error.js);
//(...) some other imports
app.use(errorHandler);

winston.add(winston.transports.File,{filename:'logFile.log'});

And in other module we've created in the course to handle errors, he requires winston and simply call to log the error. Something like this:

File: error.js

const winston = require('winston');

function errorHandler(err,req,res,next){
    winston.error(err.message,err);
    res.status(500).send("something failed");
}

module.exports = errorHandler;

After doing a test, the error is correctly written to the file, and my question is: How it works? How a setting made on the 'required version' of winston at index.js is visible from the other required version at error.js?

From index.js we are importing error.js too, so i can imagine somehow this two modules are sharing this winston object, but again, I don't understand how or where is it shared.

Again, please excuseme if I'm not using the right terms to refer anything here, I'll accept any advice.

Thanks.


Solution

  • When a module is loaded in node.js, it is cached by the require() sub-system. So, when you then require() it again, that means you'll get the exact same module as the previous one.

    So ... if you initialized the module after you first loaded it and the module stores some state that represents that intialization, then subsequent use of that module will be using the same (already initialized) module.

    And in other module we've created in the course to handle errors, he requires winston and simply call to log the error.

    It gets the same instance of the winston module that was already initialized/configured previously.

    After doing a test, the error is correctly written to the file, and my question is: How it works? How a setting made on the 'required version' of winston at index.js is visible from the other required version at error.js?

    Module caching as describe above. There's only one winston module that all are sharing so if it's initialized/configured in one place, all will use that configuration.