在 nodejs 中练习 I/O,我尝试处理包含以下行的文本文件:
{ date: 2018-02-16T16:55:35.296Z, _id: 5a870d074dfade27c4c0ce35, id: '5546721
我一行一行地选择了npm包,我最初有我的代码:
let numbers = '';
const lr = new LineByLineReader('./resources/4501-ids.txt');
lr.on('line', function (line) {
let x = line.lastIndexOf("'");
let y = line.substring(x+1);
numbers += y + ', ';
console.log(y);
count++;
});
lr.on('end', function () {
numbers = numbers.substring(0, numbers.lastIndexOf(', '));
res.send(numbers);
});
我应该得到
2345, 23465, 66435,
但我有:
2345, , 23465, , 66435,
我怀疑这是一个回车符,所以我尝试通过 if(y=== "\r\n") 来提取它,但没有成功,最后将一行更改为:
if(y)
numbers += y + ', ';
做到了。我已经完成了,但是那里的 y 是什么使行加倍并且可能起到回车作用?
最佳答案
您的文本文件内容有点不清楚,(内容不完整 + 输出与您提到的行不匹配)。但是对于您期望的输出,您可以将代码更改为
let numbers = [];
const lr = new LineByLineReader('./resources/4501-ids.txt');
lr.on('line', function (line) {
let x = line.lastIndexOf("'");
let y = line.substring(x+1);
numbers.push(y);
console.log(y);
//count++; //this is not needed numbers.length will give you this
});
lr.on('end', function () {
// numbers = numbers.substring(0, numbers.lastIndexOf(', '));
res.send(numbers.toString());
});
除此之外,如果资源文件的内容是json,你可以简单地import/require它,你会得到json对象,而不需要逐行处理它。
关于javascript - 为什么在此示例中处理我的字符串时会得到额外的 ', '?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843977/