Node.js readline 逐行讀取、寫入檔案內容的樣本,node.jsreadline

來源:互聯網
上載者:User

Node.js readline 逐行讀取、寫入檔案內容的樣本,node.jsreadline

本文介紹了運用readline逐行讀取的兩種實現,分享給大家,具體如下:

什麼是Readline

Readline是Node.js裡實現標準輸入輸出的封裝好的模組,通過這個模組我們可以以逐行的方式讀取資料流。使用require(“readline”)可以引用模組。

如下:

左邊1.log 為源檔案

右邊1.readline.log為複製後的檔案

下邊為命令列輸出

實現方式一:

var readline = require('readline'); var fs = require('fs'); var os = require('os'); var fReadName = './1.log'; var fWriteName = './1.readline.log'; var fRead = fs.createReadStream(fReadName); var fWrite = fs.createWriteStream(fWriteName); var objReadline = readline.createInterface({  input: fRead, // 這是另一種複製方式,這樣on('line')裡就不必再調用fWrite.write(line),當只是純粹複製檔案時推薦使用 // 但檔案末尾會多算一次index計數 sodino.com // output: fWrite, // terminal: true });   var index = 1; objReadline.on('line', (line)=>{  var tmp = 'line' + index.toString() + ':' + line;  fWrite.write(tmp + os.EOL); // 下一行  console.log(index, line);  index ++; });  objReadline.on('close', ()=>{  console.log('readline close...'); }); 

實現方式二:

var readline = require('readline'); var fs = require('fs'); var os = require('os');  var fReadName = './1.log'; var fWriteName = './1.readline.log'; var fRead = fs.createReadStream(fReadName); var fWrite = fs.createWriteStream(fWriteName);  var enableWriteIndex = true; fRead.on('end', ()=>{  console.log('end');  enableWriteIndex = false; });  var objReadline = readline.createInterface({  input: fRead,  output: fWrite,  terminal: true });  var index = 1; fWrite.write('line' + index.toString() +':'); objReadline.on('line', (line)=>{  console.log(index, line);  if (enableWriteIndex) {  // 由於readline::output是先寫入後調用的on('line')事件,  // 所以已經讀取檔案完畢時就不需要再寫行號了... sodino.com  index ++;  var tmp = 'line' + index.toString() + ':';  fWrite.write(tmp);  } }); objReadline.on('close', ()=>{  console.log('readline close...'); }); 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.