简体   繁体   English

如果 Node.js 的最后一行中没有 \n,则检测新行

[英]Detect new line if no \n in the last line in Node.js

I have data in buffer and I am processing it line by line.我在缓冲区中有数据,我正在逐行处理它。

In buf I have following data在 buf 我有以下数据

name,email,phn
test1,test1@example.com,1234567890
test2,testt2@example.com,1234567891

The last line doesn't have new line so my loop is working only 2 times but it should work for 3 times because buf has 3 line of record最后一行没有新行,所以我的循环只工作了 2 次,但它应该工作 3 次,因为 buf 有 3 行记录

To detect line break I am using below script要检测换行符,我正在使用以下脚本

   var stream = fs.createReadStream('file.txt', { flags: 'r', encoding: 'utf-8' });
     stream.on('data', async function (d) {
     buf += d.toString();
     var pos;
    while ((pos = buf.indexOf('\n')) >= 0) { 
    if (pos == 0) { 
     buf = buf.slice(1); // discard it
     continue; 
    }
    var line = buf.slice(0, pos).substr(0, buf.slice(0, pos).length);
    //processing logic
        }

The best way is to trim it (to make sure the ending newline is gone), then to split it on '\n' :最好的方法是trim它(以确保结束换行符消失),然后将其拆分为'\n'

const lines = buf.trim().split("\n");

for (const line of lines) {
    console.log("found line:", line);
}

If you want to keep using indexOf for whatever reason, then just add a single '\n' to the end (trimming the string first to make sure you don't end up with two \n s):如果您出于某种原因想继续使用indexOf ,则只需在末尾添加一个'\n' (首先修剪字符串以确保您不会以两个\n结束):

buf = buf.trim() + "\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM