Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Last active December 1, 2022 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolaj86/9f45bd3a27d3f7f06dd5227395939aa7 to your computer and use it in GitHub Desktop.
Save coolaj86/9f45bd3a27d3f7f06dd5227395939aa7 to your computer and use it in GitHub Desktop.

See article at https://therootcompany.com/blog/pipe-node-streams-the-right-way/.

In essense, this is the happy path:

This is the Happy Path order of stream events - when all the handlers are connected correctly, in the right order, and there are no errors.

ReadableStream WritableStream
'pipe'
'open' (files)
'ready' (files)
'readable' (1+)
'drain' (0+)
'end'
'finish'
'unpipe'
'close'
'close'
'use strict';
//
// Change these to simulate errors
//
let forceReadError = false;
let forceWriteError = false;
let handleErrors = true;
let FsStream = require('node:fs');
let rs = FsStream.createReadStream(__filename);
if (forceReadError) {
rs = FsStream.createReadStream('/doesntexist/.enoent');
}
let ws = FsStream.createWriteStream(__filename + '.junk');
if (forceWriteError) {
ws = FsStream.createWriteStream('/doesntexist/.junk');
}
if (handleErrors) {
rs.once('error', function () {
// WritableStream must be closed manually on (read) error
console.log('rs:error -> ws.end()');
ws.end();
});
} else {
rs.once('error', function (err) {
console.log('rs error (unhandled)', err);
});
}
rs.once('open', function () {
console.log('rs open');
});
rs.once('ready', function () {
console.log('rs ready');
});
rs.once('readable', function () {
console.log('rs readable');
});
rs.once('close', function () {
console.log('rs close');
});
rs.once('end', function () {
console.log('rs end');
});
rs.once('finish', function () {
console.log('rs finish');
});
///*
rs.on('readable', function () {
for (let chunk = rs.read(); chunk; chunk = rs.read()) {
console.log('chunk', chunk.length);
// process `chunk`
}
});
//*/
if (handleErrors) {
ws.once('error', function () {
// ReadableStream must be closed manually on (write) error
console.log('ws:error -> rs.close()');
rs.close();
});
} else {
ws.once('error', function (err) {
console.log('ws error (unhandled)', err);
});
}
ws.once('drain', function () {
console.log('ws drain');
});
ws.once('pipe', function () {
console.log('ws pipe');
});
ws.once('unpipe', function () {
console.log('ws unpipe');
});
ws.once('close', function () {
console.log('ws close');
});
ws.once('end', function () {
console.log('ws end');
});
ws.once('finish', function () {
console.log('ws finish');
});
rs.pipe(ws);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment