ga-wdi-boston / node-api

Other
0 stars 100 forks source link

Talk about readline #19

Open raq929 opened 7 years ago

raq929 commented 7 years ago

I worry a bit about the time of this lesson - adding more to it will make it a tight or impossible 3.

With that caveat, we want to show something like this. @gaand could you expound a bit on why we want to include this material?

const sumLinesOfArbitraryLengthFile = (filename, callback) => {
  const rl = require('readline');
  const rli = rl.createInterface({
    input: fs.createReadStream(filename),
  });
  let lno = 0;
  let sum = 0;
  rli.on('line', (line) => {
    lno++;
    sum += +line;
  });
  rli.on('close', () => {
    let error = isNaN(sum) && new Error(`line ${lno}: not a number`);
    callback(error, sum);
  });
};
gaand commented 7 years ago

I removed sync from the title.

gaand commented 7 years ago

Prefer readline to read text files. We didn't do this before because readline was still experimental.