'NodeJS : Share a log module instance inside my app

I create for my project a log module and i am actually creating a new instance in all module to allow them to log in cli with the right syntax,color conf etc.

For example (a simplified example)

// index.js

const {Log,Ansi} = require("./class/log.js");
const Tool       = require("./class/tool.js");
const argv       = require("yargs").argv;

let log = new Log({
   levelIcon:true,
   powerlineRoot:{
       name:"root",
       backgroundColor:Ansi.BLACK_BRIGHT,
       text: "myappName"
   }
});

let tool = new Tool(argv.toolName,argv.envName)

tool.run().then(() => {
   log.print("Tool is running","info");
}).catch((err) => {
   log.print(err,"critical");
});
// tool.js

const {Log,Ansi} = require("./log.js");

class Tool {

    let log = new Log({
        levelIcon:true,
        powerlineRoot:{
            name:"root",
            backgroundColor:Ansi.BLACK_BRIGHT,
            text: "myappName"
        }
    });

    run(){
        
        return new Promise((resolve, reject) => {
            resolve()
        }

    }
}

module.exports = Tool

I am wondering if there is a way to create only one instance in my index.js and share it with the instance of modules like Tools. I don't know if it's possible but i think that it will be less memory consumption to share one instance of Log than creating multiple one

I hope that my question is enough clear. Feel free to ask me more information if needed



Solution 1:[1]

Like @jjsingh says i use global variable to store the object.

Not sure it's the better way but for the moment it resolve my issue.

        global.log = new Log({
             levelIcon:true,
             powerlineRoot:{
                 name:"root",
                      color:{
                          background:Ansi.BLUE_SEA,
                          foreground:Ansi.RED,
                 },
                 text:global.conf.get("infos").name
            }
        });

Solution 2:[2]

Yes you can do that absolutely. Since the entry is index.js you can consider it will finally run as if it was a single file, in a single thread. You can create one more module logger.js like:

const {Log,Ansi} = require("./class/log.js");


const logger = new Log({
   levelIcon:true,
   powerlineRoot:{
       name:"root",
       backgroundColor:Ansi.BLACK_BRIGHT,
       text: "myappName"
   }
});
module.exports = logger;

Now you can just import logger and use it like:

const logger = require("./logger")
logger.print("hello world!");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jjsingh