【问题标题】:why I get an additional ', ' when processing my strings in this example?为什么在这个例子中处理我的字符串时我得到一个额外的','?
【发布时间】:2018-02-17 17:28:41
【问题描述】:

在 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 是什么使行加倍并可能起到回车的作​​用?

【问题讨论】:

    标签: javascript node.js return line feed


    【解决方案1】:

    您的文本文件内容有点不清楚,(不完整的内容+输出与您提到的行不匹配)。但是有了您期望的输出,您可以将代码更改为

    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对象,不需要逐行处理。

    【讨论】:

    • 嗯,文件的内容就是这样:用不同的数字重复那一行。我只是在胡闹和练习。我使用 nodepad 从数字末尾截断每一行,逐行执行此练习。谢谢,我得到了我想要的答案,但仍然不明白为什么','重复!
    猜你喜欢
    • 2018-07-29
    • 2015-06-20
    • 2019-08-19
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多