Moduł strumienia Node.js

❮ Wbudowane moduły


Przykład

Napisz do strumienia zapisywalnego:

var http = require('http');

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

Definicja i użycie

Moduł Stream zapewnia sposób obsługi danych przesyłanych strumieniowo.

Istnieją dwa rodzaje strumieni: do odczytu i do zapisu.

Przykładem czytelnego strumienia jest obiekt odpowiedzi , który otrzymujesz podczas pracy z metodą http.createServer().

Przykładem strumienia zapisywalnego jest obiekt żądania , który otrzymujesz podczas pracy z metodą http.createServer().


Składnia

Niektóre metody zwracają odczytywalny/zapisywalny obiekt stream, taki jak http.createServer(), a jeśli tak jest, nie trzeba dołączać modułu stream.

W przeciwnym razie składnia dołączania modułu Stream do aplikacji:

var stream = require('stream');

Czytelne właściwości i metody strumienia

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

Właściwości i metody strumienia zapisywalnego

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

❮ Wbudowane moduły