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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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!");

Method 2

Like @jjsingh says i use global to store the object. Not sure it’s the better way but for the moment it resolve my issue.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x