Node.js 可讀/可寫流

2018-02-16 18:28 更新

使用可讀流

可讀流的最重要的事件是“readable”。

當(dāng)存在要從流讀取的新數(shù)據(jù)時(shí)引發(fā)可讀事件。

我們可以調(diào)用流上的讀取函數(shù)從流中讀取數(shù)據(jù)。

如果這是流的結(jié)尾,read函數(shù)返回null。

將以下代碼保存為basic.js。

process.stdin.on("readable", function () { 
    var buf = process.stdin.read(); 
    if (buf != null) {
       console.log("Got:");
       process.stdout.write(buf.toString()); 
    } else {
       console.log("Read complete!"); 
    } 
}); 

以下代碼顯示了如何從命令行將數(shù)據(jù)導(dǎo)入process.stdin。

$ echo "foo bar bas" | node basic.js 
Got: 
"foo bar bas" 
Read complete! 

寫入可寫流

要寫入流,請(qǐng)調(diào)用 write 以寫入一些數(shù)據(jù)。

當(dāng)你完成寫入,調(diào)用end。

你可以使用 end 成員函數(shù)寫入一些數(shù)據(jù)。

var fs = require("fs"); 
var ws = fs.createWriteStream("message.txt"); 

ws.write("this is a test"); 
ws.end("bas"); 
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)