Created
April 25, 2022 20:06
-
-
Save mikedamage/9316df47c3c8e5b2aceb815cd3c82b83 to your computer and use it in GitHub Desktop.
Get size of piped STDIN in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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