Skip to content

Instantly share code, notes, and snippets.

@derhuerst
Last active January 3, 2021 14:22
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 derhuerst/42ab81b6d8ea5e05b4e2bfe83f702216 to your computer and use it in GitHub Desktop.
Save derhuerst/42ab81b6d8ea5e05b4e2bfe83f702216 to your computer and use it in GitHub Desktop.
stream.pipeline & pump with process.stdout 🤔
'use strict'
const {randomBytes} = require('crypto')
const {Readable, PassThrough, pipeline} = require('stream')
const pump = require('pump')
const random = (amount) => {
let bytes = 0
function read (size) {
size = Math.min(size, amount - bytes)
bytes += size
const end = bytes === amount
const that = this
setTimeout(() => {
that.push(randomBytes(size))
if (end) that.push(null)
}, 100)
}
return new Readable({read})
}
const printRandom = (pipeFn, wrapStdout, cb) => {
console.error('pipeFn', pipeFn.name, 'wrapStdout', wrapStdout)
let dest = process.stdout
if (wrapStdout) {
dest = new PassThrough()
dest.pipe(process.stdout)
}
pipeFn(
random(10 * 1024), // 10kb
dest,
(err) => {
if (err) {
console.error(err)
process.exit(1)
}
console.error('done')
cb()
},
)
}
const pipeFn = ({pipeline, pump})[process.argv[2]]
const wrapStdout = process.argv[3] === 'true'
printRandom(pipeFn, wrapStdout, () => {
printRandom(pipeFn, wrapStdout, () => {
printRandom(pipeFn, wrapStdout, () => {})
})
})
#!/bin/sh
node -v
# v15.5.0
node random.js pipeline false | wc -c
# pipeFn pipeline wrapStdout false
# done
# pipeFn pipeline wrapStdout false
# 10240
node random.js pipeline true | wc -c
# pipeFn pipeline wrapStdout true
# done
# pipeFn pipeline wrapStdout true
# done
# pipeFn pipeline wrapStdout true
# done
# 30720
node random.js pump false | wc -c
# pipeFn pump wrapStdout false
# 10240
node random.js pump true | wc -c
# pipeFn pump wrapStdout true
# done
# pipeFn pump wrapStdout true
# done
# pipeFn pump wrapStdout true
# done
# 30720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment