NodeJS 记录器:删除尾随换行符
NodeJS Logger: Remove trailing newline
我正在尝试构建一个自定义 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, Whosebug 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) );
我正在尝试构建一个自定义 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, Whosebug 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) );