Skip to content

Instantly share code, notes, and snippets.

@mikedamage
Created April 25, 2022 20:06
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 mikedamage/9316df47c3c8e5b2aceb815cd3c82b83 to your computer and use it in GitHub Desktop.
Save mikedamage/9316df47c3c8e5b2aceb815cd3c82b83 to your computer and use it in GitHub Desktop.
Get size of piped STDIN in Node
#!/usr/bin/env node
// Borrowed and simplified from pretty-bytes by Sindre Sorhus
// https://github.com/sindresorhus/pretty-bytes/blob/main/index.js
function prettyBytes(num) {
const UNITS = [
'b',
'kb',
'mb',
'gb',
'tb',
]
if (num === 0) return `0 ${UNITS[0]}`
const exponent = Math.min(Math.floor(Math.log10(num) / 3), UNITS.length - 1)
const unit = UNITS[exponent]
const scaledNum = num / 1000 ** exponent
return `${scaledNum.toLocaleString()} ${unit}`
}
let size = 0
process.stdin.on('data', (chunk) => {
size += chunk.length
})
process.stdin.on('end', () => {
console.log(prettyBytes(size))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment