node 按行读取文件

时间:2021-04-16 18:47:56
  1. var readline = require('readline');
  2. var fs = require('fs');
  3. var os = require('os');
  4. var fReadName = './1.log';
  5. var fWriteName = './1.readline.log';
  6. var fRead = fs.createReadStream(fReadName);
  7. var fWrite = fs.createWriteStream(fWriteName);
  8. var enableWriteIndex = true;
  9. fRead.on('end', ()=>{
  10. console.log('end');
  11. enableWriteIndex = false;
  12. });
  13. var objReadline = readline.createInterface({
  14. input: fRead,
  15. output: fWrite,
  16. terminal: true
  17. });
  18. var index = 1;
  19. fWrite.write('line' + index.toString() +':');
  20. objReadline.on('line', (line)=>{
  21. console.log(index, line);
  22. if (enableWriteIndex) {
  23. // 由于readline::output是先写入后调用的on('line')事件,
  24. // 所以已经读取文件完毕时就不需要再写行号了... sodino.com
  25. index ++;
  26. var tmp = 'line' + index.toString() + ':';
  27. fWrite.write(tmp);
  28. }
  29. });
  30. objReadline.on('close', ()=>{
  31. console.log('readline close...');
  32. });