Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - read line by line from file, perform async action for each line and resume

Tags:

node.js

I'm trying to read a file line by line, perform some action that has a callback and when the function finishes to resume line reading. For example:

var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var instream = fs.createReadStream('./phrases.txt');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);
rl.on('line', function (line) {
  rl.pause();
  setTimeout(function () {
    console.log('resuming');
    rl.resume();
  }, 2000);
});

I was under the impression the example above should basically read a line, wait for 2 seconds, console.log and then continue to the next line. What really happens is that it waits for the first 2 seconds and then spews out lots of console.log

like image 491
Or Weinberger Avatar asked Jan 18 '15 12:01

Or Weinberger


People also ask

How do I read a file line by line in node?

Here's the easiest way to read lines from a file, without any external modules: const fs = require('fs'); const readline = require('readline'); async function processLineByLine() { const fileStream = fs. createReadStream('input. txt'); const rl = readline.

How do I read the next line in node JS?

Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');

Is Async a line reader?

It is asynchronous, so one rl. on doesn't wait for the previous one to complete. It fires whenever the next line has been read, which should be pretty fast.

What is createInterface in node JS?

createInterface( process. stdin, process. stdout); The method createInterface() takes two parameters – the input stream and output stream – to create a readline interface.


1 Answers

Line by Line module helps you reading large text files, line by line, without buffering the files into memory.

You can process the lines asynchronously. This is the example provided:

var LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

lr.on('error', function (err) {
    // 'err' contains error object
});

lr.on('line', function (line) {
    // pause emitting of lines...
    lr.pause();

    // ...do your asynchronous line processing..
    setTimeout(function () {

        // ...and continue emitting lines.
        lr.resume();
    }, 100);
});

lr.on('end', function () {
    // All lines are read, file is closed now.
});
like image 161
Javier Ferrero Avatar answered Sep 17 '22 14:09

Javier Ferrero