Node.js V6.9.4
流(stream)在node中是1個用于處理流數據的抽象接口,node中很對對象都是基于流的,如HTTP服務器,process.stdout要求
流是可讀、可寫的,或既可讀有可寫,并且所有流都是EventEmitter的實例
流主要用于實現1個copy
方法
* const stream = require(‘stream’) *
1.流的4種類型
2.buffer
* 可讀流和可寫流都將數據存儲在內部緩沖區buffer中,當調用stream.push(chunk)時,數據被緩沖在可讀流中,如果用戶沒有調用stream.read()讀取流,那末在緩沖區中的流將會被1直存儲 *
* 如果讀緩沖區區中的buffer到達指定大小,則再次讀取的流將不會被緩存,stream.write()也1樣,1旦到達閾值,將返回false *
* stream.pipe()方法很好的解決上面的閾值問題, pipe()的目的在于將數據的緩沖限制在可接受的水平,被稱為管道*
3.1個Node.js官網例子
const http = require('http');
const server = http.createServer( (req, res) => {
// req is an http.IncomingMessage, which is a Readable Stream
// res is an http.ServerResponse, which is a Writable Stream
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added
req.on('data', (chunk) => {
body += chunk;
});
// the end event indicates that the entire body has been received
req.on('end', () => {
try {
const data = JSON.parse(body);
// write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337);
// $ curl localhost:1337 -d '{}'
// object
// $ curl localhost:1337 -d '"foo"'
// string
// $ curl localhost:1337 -d 'not json'
// error: Unexpected token o
* 上例中: 可寫流(res)暴露方法(write()、end()),這兩個方法被用于將數據寫入流中,可讀流使用EventEmitter來通知利用程序什么時候可以讀取流中的數據 *
4.可寫流
* 可寫流實際上是1塊地方,就是寄存讀取的數據的地方,或可以說內存 *
// 新建可寫流: 方法1
const Writable = require('stream').Writable;
class MyWritable extends Writable {
constructor(options) {
// Calls the stream.Writable() constructor
super(options);
}
}
// 新建可寫流: 方法2
const Writable = require('stream').Writable;
const util = require('util');
function MyWritable(options) {
if (!(this instanceof MyWritable))
return new MyWritable(options);
Writable.call(this, options);
}
util.inherits(MyWritable, Writable);
// 新建可寫流: 方法3
const Writable = require('stream').Writable;
const myWritable = new Writable({
write(chunk, encoding, callback) { // write方法為必須
// ...
},
writev(chunks, callback) {
// ...
}
});
常見的可寫流
process.stdout, process.stderr
5.可讀流
* 可讀流是讀取數據源的抽象,即數據寄存的地方,或說內存 *
// 新建可讀流:方法1
const Readable = require('stream').Readable;
class MyReadable extends Readable {
constructor(options) {
// Calls the stream.Readable(options) constructor
super(options);
}
}
// 新建可讀流:方法2
const Readable = require('stream').Readable;
const util = require('util');
function MyReadable(options) {
if (!(this instanceof MyReadable))
return new MyReadable(options);
Readable.call(this, options);
}
util.inherits(MyReadable, Readable);
// 新建可讀流:方法3
const Readable = require('stream').Readable;
const myReadable = new Readable({
read(size) { //異步方法
// ...
}
push(chunk[,encoding]) //將數據chunk放進可讀流隊列里面
});
常見的可寫流
6.流的利用
* 對小文件,可使用可讀流講數據存在內存中,然后用可寫流講數據讀取 *
const fs = require('fs');
var src = fs.readFileSync('/home/clx/old.sql');
fs.writeFileSync('/home/clx/new.sql', src); // 在/home/clx目錄下會出現1個new.sql文件
* 上面的例子中當old.sql不大時沒有問題,但是當old.sql變成1部電影或幾個G的’動作片’,那程序就會崩潰,有兩種方法解決:1種是利用可讀流暫停,1種是利用pipe管道 *
7.管道
** readable.pipe()將Writable流附加到可讀流,使其自動切換到寫流模式,并將其所有數據推送到附加的Writable。管道將自動管理流數據,使得當可讀流大于可寫流時數據不被丟失,或內存被過量的占用,
即管道是1邊讀1遍寫 **
const fs = require('fs');
const Readable = require('stream').stream;
let readable = new Readable({
read(size) { //為可寫流添加read方法,可讀流必須有該方法
this.push('/home/clx/old.mp4');
}
});
const writable = fs.createWriteStream('/home/clx/new.mp4');
// 管道讀寫,結束后在/home/clx/目錄下生成new.mp4文件
readable.pipe(writable, {end: false}); // => 管道讀寫完后觸發讀寫流'end'事件
readable.on('end', () => { // => 為讀寫流注冊'end'事件
write.end('End');
})
* Node.js很多方法都是基于流的,只是被封裝好了,我們看不見,流是很多利用的基礎,主要用來處理2進制文件 *
下一篇 Andfix學習記錄