我为我的项目创建了一个日志模块,我实际上正在所有模块中创建一个新实例,以允许他们以正确的语法、颜色、conf等方式登录cli。
例如(一个简化的例子)
// 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我想知道是否有一种方法可以在我的index.js中创建一个实例并与工具等模块的实例共享。我不知道是否可能,但我认为与创建多个实例相比,共享一个日志实例的内存消耗更少
我希望我的问题足够清楚。如果需要的话,随时可以问我更多的信息。
发布于 2022-03-28 11:44:22
就像@jjsingh说的那样,我使用全局变量来存储对象。
不确定这是不是更好的方法,但目前它解决了我的问题。
global.log = new Log({
levelIcon:true,
powerlineRoot:{
name:"root",
color:{
background:Ansi.BLUE_SEA,
foreground:Ansi.RED,
},
text:global.conf.get("infos").name
}
});发布于 2022-03-05 18:27:55
是的你绝对可以做到。因为条目是index.js,所以您可以认为它最终会像在单个线程中的单个文件一样运行。您可以再创建一个模块logger.js,如:
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;现在您只需导入记录器并使用它,如下所示:
const logger = require("./logger")
logger.print("hello world!");https://stackoverflow.com/questions/71355173
复制相似问题