STREAMS RECAP
A stream is a flow of data.
Could be numbers, binary, text…
Copyright By PowCoder代写 加微信 powcoder
Data that is written out by your application.
Examples: files, chat messages, data extraction, image processing
BUILT-IN: If you want to write out to a file, use
THE FS OBJECT
an output stream.
STREAM.WRITEABLE
const fs = require(‘fs’);
const stream = fs.createWriteStream(‘./data.txt’); stream.on(‘open’, ( ) => {
console.log(‘data file is open’) });
STREAM. WRITEABLE EVENTS
The ‘close’ event is emitted when the stream has been closed. No more events will be emitted.
STREAM. WRITEABLE EVENTS
If a call to stream.write(chunk) returns false, the ‘drain’ event will be emitted when it is appropriate to resume writing data to the stream.
STREAM.WRITEABLE DRAIN
STREAM. WRITEABLE EVENTS
The finish event is emitted after the stream.end() method has been invoked
STREAM.READABLE EVENTS
The ‘pipe’ event is emitted when the stream.pipe() method is called on a readable stream.
PIPE EXAMPLE
const writer = getWritableStreamSomehow(); const reader = getReadableStreamSomehow();
writer.on(‘pipe’, (src) => {
console.error(‘something is piping into the writer’);
}); reader.pipe(writer);
STREAM.WRITEABLE EVENTS
The ‘unpipe’ event is emitted when the stream.unpipe() method is called on a Readable stream
UNPIPE EXAMPLE
const writer = getWritableStreamSomehow(); const reader = getReadableStreamSomehow();
writer.on(‘unpipe’, (src) => {
console.error(‘Something has stopped piping to the writer.’);
reader. pipe(writer); reader. unpipe(writer);
WRITING STREAMS
const options = { ‘encoding’: ‘utf8’};
const fs = fs.createWriteStream(‘data.out’, options, ( ) => {
/* Callback for when this operation is finished. */
WRITING STREAMS (2)
• _stream.on(‘end’, ( ) => {
• /* Callback for when there is no • more data to write. */
WRITING STREAMS (3)
_stream.write(‘data processing complete’); _stream.write(‘check the logs’);
_stream.end( ( ) => {
/* The optional callback function is here as a listener for the ‘finish’ event. */
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com