وحدة دفق 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 |