Search code examples
javascriptnode.js

Read lines synchronously from file in Node.js


I need to parse a file line by line in the following format with Node.js:

13
13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3

It represents a graph. The first two lines are the number of edges and vertexes, followed by the edges.

I can accomplish the task with something like:

var fs = require('fs');
var readline = require('readline');
var read_stream = fs.createReadStream(filename);
var rl = readline.createInterface({
    input: read_stream
});
var c = 0;
var vertexes_number;
var edges_number;
var edges = [];
rl.on('line', function(line){
    if (c==0) {
        vertexes_number = parseInt(line);
    } else if (c==1) {
        edges_number = parseInt(line);
    } else {
        edges.push(line.split(' '));
    }
    c++;
})
.on('end', function(){
    rl.close();
})

I understand this kind of things might not be what Node.js was thought for, but the cascaded if in the line callback does not really look elegant / readable to me.

Is there a way to read synchronously lines from a stream like in every other programming language?

I'm open to use plugins if there is not a built-in solution.

[EDIT]

Sorry, I should have made clearer that I would like to avoid loading the whole file in memory beforehand


Solution

  • This project on github.com does exactly what I needed:

    https://github.com/nacholibre/node-readlines

    var readlines = require('n-readlines');
    var liner = new readlines(filename);
    
    var vertexes_number = parseInt(liner.next().toString('ascii'));
    var edges_number = parseInt(liner.next().toString('ascii'));
    var edges = [];
    var next;
    while (next = liner.next()) {
        edges.push(next.toString('ascii').split(' '));
    }