Mr.
Mr.

Reputation: 10142

NodeJS - readline pause and resume event emitter (read line by line)

I am using Node v.0.8.9, and its module readline. I cannot use fs.readFile() since I get EISDIR error.

I would like to read line by line from a file, do some work, and only then (when the work is complete) to read the next line. Thus, I tried the following snippet (see below) but when changing the for with some synchronous work, it does not behave synchronously.

var fs = require('fs');
var readline = require("readline");
var filename = process.argv[2];

readline.createInterface({
    input: fs.createReadStream(filename),
    terminal: false
}).on("line", function(line){
   this.emit("pause", line);
}).on("pause", function(line) {
    console.log("pause");
    console.log(line);
    console.log("doing some work");
    for (var i = 0; i < 1000000000; ++i);
    this.emit("resume");
}).on("resume", function() {
    console.log("resume");
}).on("close", function() {
    console.log("close");
});

Could one shed the light on the issue?

Upvotes: 3

Views: 4051

Answers (2)

Mr.
Mr.

Reputation: 10142

Although it is common to read line by line from a file, NodeJS has no implementation for supporting such big files. Hence, you will need to implement it using a buffer.

Here is one which works beautifully - http://blog.jaeckel.com/2010/03/i-tried-to-find-example-on-using-node.html

Upvotes: 2

JP Richardson
JP Richardson

Reputation: 39435

Just a hunch.... try actually calling pause() instead of emitting the pause event.

That is, change:

this.emit("pause", line);

to...

this.pause();

Let me know if this works.

Upvotes: 0

Related Questions