Reading Int Values from file, all in one line

时间:2019-03-19 14:55:47

标签: javascript arrays node.js filesystems

Im here because I have weird problem. I wanted to read some int values from txt file. All of them are in one line. To do that simple task I created very simple node.js code:

const readValues = fs.createReadStream(('txt\\' + file[0]));
readValues.setEncoding();                  //It's because I want String here
readValues.on('data', (chunk) => {
    chunk = chunk.trim();
    chunk.split(' ').forEach(value => {
        values.push(parseInt(value, 10));
    });
});

Then Im getting this warning

But when I add console.log to show those values in console:

const readValues = fs.createReadStream(('txt\\' + file[0]));
readValues.setEncoding();                  //It's because I want String here
readValues.on('data', (chunk) => {
    chunk = chunk.trim();
    chunk.split(' ').forEach(value => {
        console.log(value);    // here
        values.push(parseInt(value, 10));
    });
});

Then all those values are shown in the console and above warning dosen't here. I tested also readFileSync:

const readValues = fs.readFileSync(('txt//' + file[0]), 'utf8').trim();
readValues.split(' ').forEach(value => {
    values.push(parseInt(value, 10));
});
//console.log(values);

But the outcome is reversed - Im getting that error when I display those values, but when I don't display that, I don't get it: https://imgur.com/a/yehrmX7 This is happening in LTS version of node and in 11.11.0. I ran out of ideas and I didn't found any solution. Maybe someone from u know where do I made some mistake ?? I would be grateful for some help.

1 个答案:

答案 0 :(得分:0)

问题是我以错误的方式初始化了数组。

我用这种方式:

const values = Array.prototype;

应该是这样的:

const values = new Array();

好的,我的错。我自欺欺人是因为我想在第一步中创建完美的代码。我不是完美的人。对不起,打扰您了。我把其他人的答案留在这里。

相关问题