bytes.js
bytes.js copied to clipboard
Force convert to a level
ei, if I want to display disk usage. Used converts to 20 mb, max to 2tb. Be nice to be able to have them same unit.
something like:
var total = bytes(disk.total);
var used = bytes(disk.used, total); //or total.match(/[a-z]/i)
@tj After the merge of the PR #20 I guess it won't be much trouble to add it as a second parameter.
For the bytes(number value, object [options]): string|null
adding an property units
which would result as the following:
bytes(1000, {units: null});
// output: '1000B'
bytes(1000, {units: 'kB'});
// output: '0.97656kB'
Which would also work with strings:
bytes('1MB', {units: 'kB'});
// output: '1024kB'
And maybe adding a shorthand:
bytes(1000, 'kB');
// output: '0.97656kB'
bytes('1MB', 'kB');
// output: '1024kB'
Which would be possible by determining if the options parameter is a string or an object. However that raises the case of what to do when the units passed are wrong? The current behavior is to return null which is unambiguous since if you do bytes('1ky')
, the only error possible comes from the unit. But if you do so with bytes('1My', 'ku')
or bytes('1mb', 'ku')
we do not know from where the error comes from (although easy to guess).
Some possible solutions:
- Keep the current behavior which returns
null
and let the user guess his error - Throw an error to display a more user friendly error, but I don't like the idea to have a try/catch for using this utility
I prefer the first solution.
ping @dougwilson
@theofidry, I'm impartial to the choice.