【问题标题】:NodeJS Logger: Remove trailing newlineNodeJS Logger:删除尾随换行符
【发布时间】:2020-08-25 17:53:50
【问题描述】:

我正在尝试构建一个自定义 NodeJS 记录器,它将数据记录到文件中。
要附加数据,我使用 fs.createWriteStream 和 a 标志。

var fs = require("fs");

var stream = fs.createWriteStream("./test.log", {
   encoding: "utf-8",
   flags: "a",
   autoClose: true
});

// Data to log to file
var data = {
   timestamp: new Date().toJSON(),
   message: "OK"
};

// Write data
stream.write(JSON.stringify(data) + "\n");

记录几次会生成如下所示的文件:

{"timestamp":"2020-08-25T17:45:27.733Z","message":"OK"}
{"timestamp":"2020-08-25T17:45:34.820Z","message":"OK"}
{"timestamp":"2020-08-25T17:45:41.142Z","message":"OK"}
(Heres a newline, StackOverflow removes them)

我的问题是,我不知道如何删除尾随换行符。
我想过在每个日志条目之前添加换行符,但这需要我检测文件的开头(我没有找到这样做的方法)。

如果可能的话,删除尾随换行符的最佳方法是什么? 任何帮助将不胜感激!

【问题讨论】:

    标签: javascript node.js logging newline fs


    【解决方案1】:

    你需要检查文件是否为空:

    var fs = require("fs");
    
    var stream = fs.createWriteStream("./test.log", {
       encoding: "utf-8",
       flags: "a",
       autoClose: true
    });
    
    // Data to log to file
    var data = {
       timestamp: new Date().toJSON(),
       message: "OK"
    };
    
    // Check if file is empty
    var stats = fs.statSync("./test.log");
    var isEmpty = stats["size"] == 0;
    
    // Write data
    stream.write((isEmpty ? "" : "\n") + JSON.stringify(data) );
    

    【讨论】:

    • 这意味着每个条目都在第一行,这不是我想要实现的目标。
    • 在这种情况下,您需要检查文件是否为空,如果不是则添加换行符
    • 非常感谢,感谢您,我找到了解决方案。 :)
    • 我已经编辑了我的答案;你的解决方案和它类似吗?
    • 是的。不过我会接受你的回答,再次感谢!
    猜你喜欢
    • 2011-04-01
    • 2010-09-21
    • 2016-08-20
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2016-03-19
    相关资源
    最近更新 更多