问题描述
我正在尝试构建自定义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)
我的问题是,我不知道如何删除尾随的换行符。
我曾考虑过在每个日志条目之前添加换行符,但这需要我检测文件的开头(我没有找到执行此操作的方法)。
如果可能的话,删除尾随换行符的最佳方法是什么? 任何帮助将不胜感激!
解决方法
您需要检查文件是否为空:
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) );