Skip to content

Instantly share code, notes, and snippets.

@four43
Last active February 21, 2021 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save four43/46fd38fd0c929b14deb6f1744b63026a to your computer and use it in GitHub Desktop.
Save four43/46fd38fd0c929b14deb6f1744b63026a to your computer and use it in GitHub Desktop.
Node.js Stream Close Testing
const fs = require('fs');
const stream = require('stream');
let readStream,
passThrough,
writeStream,
transform;
const inputPath = '/tmp/input.txt';
const outputPath = '/tmp/output.txt';
function setup() {
fs.writeFileSync(inputPath, "This is the input.");
fs.writeFileSync(outputPath, "");
readStream = fs.createReadStream(inputPath);
passThrough = new stream.PassThrough({allowHalfOpen: false});
writeStream = fs.createWriteStream(outputPath);
transform = new stream.Transform({
allowHalfOpen: false,
transform: (chunk, encoding, cb) => cb(null, chunk)
});
addDebugEvents(readStream, 'read');
addDebugEvents(writeStream, 'write');
addDebugEvents(passThrough, 'passThrough');
addDebugEvents(transform, 'transform');
}
function test1(cb) {
console.log("Test 1: Read | Write\n");
const rwPipeStream = readStream.pipe(writeStream);
addDebugEvents(rwPipeStream, 'rwPipe');
readStream.on('close', () => {
console.log("Test 1 Complete.\n");
cb();
});
}
function test2(cb) {
console.log("Test 2: Transform | Write\n");
const pipeResult = transform.pipe(writeStream);
addDebugEvents(pipeResult, 'piped');
transform.on('close', () => {
console.log("Test 2 Complete.\n");
cb();
});
transform.end('hello world');
}
function addDebugEvents(stream, name) {
['close', 'drain', 'error', 'finish', 'pipe', 'unpipe', 'data', 'end', 'readable']
.map(eventName => stream.on(eventName, () => console.log(`${name}-${eventName}`)))
}
// Run it!
setup();
test1(() => setTimeout(() => {
console.log("Waited for remaining Test 1 stream events, done!\n");
setup();
test2();
}, 1000));
Test 1: Read | Write
write-pipe
read-data
read-readable
read-end
write-finish
write-unpipe
rwPipe-unpipe
rwPipe-finish
read-close
Test 1 Complete.
write-close
rwPipe-close
Waited for remaining Test 1 stream events, done!
Test 2: Transform | Write
write-pipe
transform-data
transform-readable
transform-finish
transform-end
read-data
write-finish
write-unpipe
piped-unpipe
piped-finish
read-readable
read-end
write-close
piped-close
read-close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment