Modulo di flusso Node.js
Esempio
Scrivi su un flusso scrivibile:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello
World!');
res.end();
}).listen(8080);
Definizione e utilizzo
Il modulo Stream fornisce un modo per gestire i dati in streaming.
Esistono due tipi di flussi: leggibili e scrivibili.
Un esempio di flusso leggibile è l' oggetto risposta che si ottiene quando si lavora con il metodo http.createServer().
Un esempio di flusso scrivibile è l' oggetto richiesta che si ottiene quando si lavora con il metodo http.createServer().
Sintassi
Alcuni metodi restituiscono un oggetto stream leggibile/scrivibile, come http.createServer(), e in tal caso, non è necessario includere il modulo stream.
Altrimenti, la sintassi per includere il modulo Stream nell'applicazione:
var stream = require('stream');
Proprietà e metodi del flusso leggibili
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 |
Proprietà e metodi del flusso scrivibili
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 |