javascript 在 Node JS 中仅读取文件第一行的最有效方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28747719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the most efficient way to read only the first line of a file in Node JS?
提问by Pensierinmusica
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?
想象一下,您有许多长文本文件,您只需要从每个文件的第一行提取数据(无需阅读任何其他内容)。Node JS 中最好的方法是什么?
Thanks!
谢谢!
采纳答案by Pensierinmusica
I ended up adopting this solution, which seems the most performant 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 a npm module for convenience, named "firstline".
为了方便起见,我创建了一个 npm 模块,名为“ firstline”。
Thanks to @dandavis for the suggestion to use String.prototype.slice()
!
感谢@dandavis 的使用建议String.prototype.slice()
!
回答by Jake
Please try this:
请试试这个:
https://github.com/yinrong/node-line-stream-util#get-head-lines
https://github.com/yinrong/node-line-stream-util#get-head-lines
It unpipe the upstream once got the head lines.
一旦得到头线,它就会对上游进行管道疏通。
回答by Viktor Molokostov
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:
对于这种情况,几乎有一个内置模块 - readline
. 它避免弄乱块等。代码如下所示:
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;
}
回答by Safi
//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
})
}