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

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

Thanks!

+8
javascript filesystems stream text-files
source share
3 answers

In the end, I decided to use this solution, which seems to be the most perfect I've seen so far:

var fs = require('fs'); var Q = require('q'); function readFirstLine (path) { return Q.promise(function (resolve, reject) { var rs = fs.createReadStream(path, {encoding: 'utf8'}); var acc = ''; var pos = 0; var index; rs .on('data', function (chunk) { index = chunk.indexOf('\n'); acc += chunk; index !== -1 ? rs.close() : pos += chunk.length; }) .on('close', function () { resolve(acc.slice(0, pos + index)); }) .on('error', function (err) { reject(err); }) }); } 

I created an npm module for convenience called " firstline ."

Thanks to @dandavis for suggesting using String.prototype.slice() !

+6
source share

// Here you go;

 var lineReader = require('line-reader'); var async = require('async'); exports.readManyFiles = function(files) { async.map(files, function(file, callback)) lineReader.open(file, function(reader) { if (reader.hasNextLine()) { reader.nextLine(function(line) { callback(null,line); }); } }); }, function(err, allLines) { //do whatever you want to with the lines }) } 
+1
source share

Please try the following:

https://github.com/yinrong/node-line-stream-util#get-head-lines

The upstream problem after it received the headers.

+1
source share

All Articles