Confused by Node.js readline on() method

后端 未结 1 1940
孤独总比滥情好
孤独总比滥情好 2020-12-18 08:05

I am confused by some simple behavior I see from readline on() method.

I have a file called small.csv which looks like this:



        
1条回答
  •  隐瞒了意图╮
    2020-12-18 08:21

    Because of it's asynchronous nature Node.js can be a bit tricky with this kind of things. It means that when your code is executing, it is firing the rl.on('line') handler and passing to the next call which in our case is the console.log. The problem in your actual code is not that the array is not filling up, it's that you are expecting it to be populated to early. Here is an example of how you could fix your problem:

    var rl = require('readline').createInterface({
      input: require('fs').createReadStream('small.csv')
    });
    
    global.myarray = [];
    rl.on('line', function (line) {
      console.log('Line from file:', line);
      global.myarray.push(line);
    });
    
    rl.on('close', function () {
        console.log(global.myarray);
    });
    

    In this piece of code, when there is no more line to read from, the console.log will be called and there will be some data displayed.

    0 讨论(0)
提交回复
热议问题