Search code examples
javascriptnode.jsexpresswinston

How to use a library in multiple files in Nodejs


I want to use Winston for logging in my nodejs express project. In my main file( server.js ) I have the following code :

const winston = require('winston');
winston.level = process.env.LOG_LEVEL
winston.log('info', 'Hello log files!')

I want to use this library in other files as well, so do I have to add these 2 lines to every file I want to use it or is there a better way to do it.


Solution

  • you can create customWinston.js File:

    let winston = require('winston');
    winston.level = process.env.LOG_LEVEL
    winston.log('info', 'Hello log files!')
    
    exports.customWinston = winston;
    

    and then require your custom Winston:

    let customWinston = require('./customWinston').customWinston;