I need to parse the file line by line in the following format using 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 is a graph. The first two lines are the number of edges and vertices followed by edges.
I can complete 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 that such things may not be what Node.js was thinking, but the cascading if in the line callback does not really look elegant / readable.
Is there a way to read synchronous lines from a stream, like in any other programming language?
I am open to using plugins if there is no built-in solution.
[EDIT]
Sorry, I had to clarify that I would like to avoid loading the entire file into memory in advance
Andrea Casaccia
source share