Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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!");
about 4 years ago · Juan Pablo Isaza Relatório

0

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
            }
        });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda