Node.js สตรีมโมดูล

❮ โมดูลในตัว


ตัวอย่าง

เขียนไปยังสตรีมที่เขียนได้:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Hello World!');
  res.end();
}).listen(8080);

ความหมายและการใช้งาน

โมดูลสตรีมมีวิธีการจัดการข้อมูลการสตรีม

สตรีมมีสองประเภท: อ่านได้และเขียนได้

ตัวอย่างของสตรีมที่อ่านได้คือ วัตถุ ตอบสนองที่คุณได้รับเมื่อทำงานกับเมธอด http.createServer()

ตัวอย่างของสตรีมที่เขียนได้คือ วัตถุ คำขอที่คุณได้รับเมื่อทำงานกับเมธอด http.createServer()


ไวยากรณ์

เมธอดบางวิธีคืนค่าออบเจ็กต์สตรีมที่อ่านได้/เขียนได้ เช่น http.createServer() และหากเป็นกรณีนี้ คุณไม่จำเป็นต้องรวมโมดูลสตรีม

มิฉะนั้น ไวยากรณ์สำหรับการรวมโมดูลสตรีมในแอปพลิเคชันของคุณ:

var stream = require('stream');

คุณสมบัติและวิธีการสตรีมที่อ่านได้

Method Description
isPaused() Returns true if the state of  the readable stream is paused, otherwise false
pause() Pauses the readable stream
pipe() Turns the readable stream into the specified writable stream
read() Returns a specified part of the readable stream
resume() Resumes a paused stream
setEncoding() Sets the character encoding of the readable stream
unpipe() Stops turning a readable stream into a writable stream, caused by the pipe() method
unshift() Pushes some specified data back into the internal buffer
wrap() Helps reading streams made by older Node.js versions

คุณสมบัติและวิธีการสตรีมที่เขียนได้

Method Description
cork() Stops the writable stream and all written data will be buffered in memory
end() Ends the writable stream
setDefaultEncoding() Sets the encoding for the writable stream
uncork() Flushes all data that has been buffered since the cork() method was called
write() Writes data to the stream

❮ โมดูลในตัว