[英]Write to file without overwriting with fs
I want a logger for my project.我想要一个记录器用于我的项目。 Everytime I call myConsole.log it overwrites the existing log.
每次我调用 myConsole.log 它都会覆盖现有的日志。 what can i do that the it just write it in the next line and not delete everything
我能做什么,它只是写在下一行而不是删除所有内容
const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.log'));
myConsole.log(var)
myConsole.log(var2)
myConsole.log(var3)
You can pass { flags: 'a'}
as options argument to the createWriteStream call.您可以将
{ flags: 'a'}
作为选项参数传递给createWriteStream调用。
This flag will open the file for appending instead of overwriting此标志将打开文件以进行附加而不是覆盖
I'd reccomend looking at Winston , which is a package that does great logging.我建议看一下Winston ,这是一个 package ,它可以很好地记录日志。
But with your code, you need to add the a
(append) flag to your fs writer so it writes properly rather than overwriting (default flag is w
), like so:但是对于您的代码,您需要将
a
(附加)标志添加到您的 fs 编写器,以便它正确写入而不是覆盖(默认标志是w
),如下所示:
const myConsole = new console.Console(fs.createWriteStream('./output.log', { flags: 'a' }));
See docs on createwritestream and system flags .请参阅有关createwritestream和系统标志的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.