Mô -đun luồng Node.js
Ví dụ
Viết vào một luồng có thể ghi:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello
World!');
res.end();
}).listen(8080);
Chạy ví dụ »Định nghĩa và cách sử dụng
Mô-đun Stream cung cấp cách xử lý dữ liệu truyền phát.
Có hai loại luồng: có thể đọc và có thể ghi.
Một ví dụ về luồng có thể đọc được là đối tượng phản hồi bạn nhận được khi làm việc với phương thức http.createServer().
Một ví dụ về luồng có thể ghi là đối tượng yêu cầu bạn nhận được khi làm việc với phương thức http.createServer().
Cú pháp
Một số phương thức trả về một đối tượng luồng có thể đọc/ghi, như http.createServer() và nếu đúng như vậy, bạn không cần phải đưa mô-đun luồng vào.
Mặt khác, cú pháp để đưa mô-đun Luồng vào ứng dụng của bạn:
var stream = require('stream');
Thuộc tính và phương thức luồng có thể đọc được
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 |
Thuộc tính và phương thức của luồng có thể ghi
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 |