Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to read only the first line of a file in Node JS?

Imagine you have many long text files, and you need to only extract data from the first line of each one (without reading any further content). What is the best way in Node JS to do it?

Thanks!

like image 535
Pensierinmusica Avatar asked Feb 26 '15 16:02

Pensierinmusica


1 Answers

There's a built-in module almost for this case - readline. It avoids messing with chunks and so forth. The code would look like the following:

const fs = require('fs');
const readline = require('readline');

async function getFirstLine(pathToFile) {
  const readable = fs.createReadStream(pathToFile);
  const reader = readline.createInterface({ input: readable });
  const line = await new Promise((resolve) => {
    reader.on('line', (line) => {
      reader.close();
      resolve(line);
    });
  });
  readable.close();
  return line;
}
like image 90
Viktor Molokostov Avatar answered Oct 01 '22 09:10

Viktor Molokostov