Open AlfieriChou opened 2 years ago
const readline = require('readline');
const fs = require('fs');
// 指定要读取的文件路径、起始行和结束行
const filePath = 'file.txt';
const startLine = 3; // 起始行
const endLine = 7; // 结束行
// 创建逐行读取接口
const rl = readline.createInterface({
input: fs.createReadStream(filePath) // 指定要读取的文件路径
});
let currentLine = 1;
// 逐行读取文件内容
rl.on('line', (line) => {
if (currentLine >= startLine && currentLine <= endLine) {
console.log(`Line ${currentLine}: ${line}`);
}
// 如果当前行数已经达到结束行,关闭读取接口
if (currentLine === endLine) {
rl.close();
}
currentLine++;
});
// 当文件读取完成时触发
rl.on('close', () => {
console.log('File reading completed.');
});