我正在使用 nodejs 'readline' 逐行读取文件。我正在逐行读取 .csv 文件并将其转换为 JSON。我从写“{”开始,然后每行都被解析、格式化并以“,”结尾。我想对最后一行做一些与前面几行不同的事情,即。以 '}' 而不是 ',' 结束。如何检测当前行是最后一行。
var readline = require("readline");
var fs = require("fs");
var read_in = readline.createInterface({
input: fs.createReadStream(file),
crlfDelay: Infinity
});
var write_out = fs.createWriteStream("intermediate.json")
write_out.write("{");
read_in.on("line", function (line) {
var a = line.split(",");
var b = "\"" + a[0].trim() + "\" : \"" + a[1] + "\",\r\n"
write_out.write(b);
})
read_in.on("close", function () {
write_out.write("}"); // leaves an incorrectly formatted JSON file
})