gpt4 book ai didi

javascript - nodejs createReadStream 从第n行开始

转载 作者:搜寻专家 更新时间:2023-10-31 23:26:42 27 4
gpt4 key购买 nike

为了使用 nodejs 逐行读取文本文件,我有以下代码:

var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('log.txt')
});
lineReader.on('line', function (line) {
console.log(line);
});
lineReader.on('close', function() {
console.log('Finished!');
});

有没有办法从特定行开始读取文件?

最佳答案

根据Node.js Docs您可以在创建流时同时指定 startend 选项:

options can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start at 0

// get file size in bytes
var fileLength = fs.statSync('log.txt')['size'];
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('log.txt', {
// read the whole file skipping over the first 11 bytes
start: 10
end: fileLength - 1
})
});

关于javascript - nodejs createReadStream 从第n行开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com