node.js - Node 'readline' 如何检测当前行是文件中的最后一行

标签 node.js nodejs-stream

我正在使用 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
    })

最佳答案

使用 csv 执行此操作的一种有趣方式,但它应该适用于任何类型的文档。

文档内容

one,apple
two,banana
three,orange

代码

// Load document
const originalStream = fs.readFileSync(`my_document.csv`);

// Convert document to hex
const hexStream = new Buffer.from(streambase).toString('hex')
// Output 
// 6f6e652c6170706c650a74776f2c62616e616e610a74687265652c6f72616e6765
// New lines are separated by 0a so we can assume thats the start of a new line

// Retrieve last line in hex format
const lastLineHex = hexStream.split("0a").splice(-1)[0]
// Output
// 74687265652c6f72616e6765

const convertLastLineBackToUtf = new Buffer.from(lastLineHex, 'hex').toString();
// Output
// three,orange

要检查它们是否在最后一行,您可以将其与最终输出进行比较。

关于node.js - Node 'readline' 如何检测当前行是文件中的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742649/

相关文章:

javascript - 在 NodeJS 中,如何在不手动添加换行符的情况下将行打印到文件中?

javascript - "chunk"参数必须是字符串类型或 Buffer 的实例

javascript - Async.js:在 waterfall 任务中创建的变量是否可以在另一个任务中使用?

node.js - 使用环境变量中的 token 从私有(private) Github 存储库安装 NPM 包

node.js - AWS ALB 从 lambda 返回 502 Bad Gateway

javascript - 如何在nodejs中使用事件和管道创建函数

node.js - nodejs 的 http 模块不是可以一次接收/发送整个请求/响应吗?

javascript - 在 native iOS 应用程序中使用 PassportJS 和 Nodejs 时出现错误 "The redirect_uri URL must be absolute"

node.js - 我的 Discord 机器人无法上线

javascript - 等待 foreach 完成