0

I'm using lazy and fs to read a file line-by-line (reference):

Lazy = require('lazy');
fs = require('fs');

lazy = new Lazy(fs.createReadStream(filename, {
  encoding: 'utf8'
}));

lazy.lines.forEach(function(line) {
  line = String(line);
  // more stuff...
}

The weird thing is, when an empty line is read, String(line) results in the string 0. This is a problem because I can't find a way to distinguish whether the 0 is a result of an empty line, or if the line actually contains a single character 0.

Why is it so? And how to solve this problem?

Community
  • 1
  • 1
Derek Chiang
  • 3,330
  • 6
  • 27
  • 34

1 Answers1

4

It's certainly a bug in the Lazy module, I can reproduce it.

The problem is this line:

finalBufferLength = buffers.reduce(function(left, right) { return (left.length||left) + (right.length||right); }, 0);

There's an implicit string conversion in there (so the number 0 is converted to the string "0"), because this fixes it:

finalBufferLength = buffers.reduce(function(left, right) { return Number(left.length||left) + Number(right.length||right); }, 0);

It seems Lazy was only tested with DOS-style line-endings, because when I feed it a file with those, it works just fine. Because of that, as a quick fix, I think you could use this:

lazy
  .map(function(chunk) {
    // replace Unix-style (LF) line ending with DOS-style (CRLF)
    return chunk.replace(/(?!\r)\n/g, '\r\n');
  })
  .lines
  .forEach(function(line) {
    console.log('L', line.toString());
  });
robertklep
  • 198,204
  • 35
  • 394
  • 381