admin管理员组文章数量:1400311
On Node.js we can read a file line by line using the readline
module:
var fs = require('fs');
var readline = require('readline');
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
console.log(`Line read: ${line}`);
});
But what if we want to start reading on a specific line number? I know that when we use the createReadStream
we can pass in a start
parameter. This is explained in the docs:
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file.
But here start
is one offset in bytes, so it seems plicated to use this to set the starting line.
How can we adapt this approach to start reading a file on a specific line?
On Node.js we can read a file line by line using the readline
module:
var fs = require('fs');
var readline = require('readline');
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
console.log(`Line read: ${line}`);
});
But what if we want to start reading on a specific line number? I know that when we use the createReadStream
we can pass in a start
parameter. This is explained in the docs:
options
can includestart
andend
values to read a range of bytes from the file instead of the entire file.
But here start
is one offset in bytes, so it seems plicated to use this to set the starting line.
How can we adapt this approach to start reading a file on a specific line?
Share Improve this question asked Jun 14, 2016 at 16:48 user1620696user1620696 11.4k13 gold badges62 silver badges83 bronze badges 1-
1
In order to determine where a line break occurs, you need to read the file. There's no way to just open a file and be able to jump to the byte immediately following a
\n
. – Mike Cluck Commented Jun 14, 2016 at 16:51
1 Answer
Reset to default 7You have to read the file from the beginning and count lines and start processing the lines only after you get to a certain line. There is no way to have the file system tell you where a specific line starts.
var fs = require('fs');
var readline = require('readline');
var cntr = 0;
var rl = readline.createInterface({
input: fs.createReadStream('filepath');
});
rl.on('line', function(line) {
if (cntr++ >= 100) {
// only output lines starting with the 100th line
console.log(`Line read: ${line}`);
}
});
本文标签: javascriptNodejs start reading a file on a specific lineStack Overflow
版权声明:本文标题:javascript - Node.js start reading a file on a specific line - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744256904a2597524.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论