File size string to number parser?

Hi everyone, I'm looking for a library that can parse a string such as "12.3Mb" or any other unit of measurement of information (b, kb, mb, gb, etc), and returns me the integer amount in bytes for that string. Does anyone know of something like that?
6 Replies
13eck
13eckā€¢3y ago
Here's your lib!
const giveMeBytes = (str) => {
const multiplier = {
b: 1,
kb: 1024,
mb: 1024**2,
gb: 1024**3,
tb: 1024**4,
pb: 1024**5
}

const num = Number(str.match(/\d/).toString())
const type = str.match(/[a-zA-Z]+/).toString().toLowerCase()
return `${str} is ${(num * multiplier[type]).toLocaleString()} bytes!`

}

console.log(giveMeBytes("5mb"));

console.log(giveMeBytes("10TB"));
const giveMeBytes = (str) => {
const multiplier = {
b: 1,
kb: 1024,
mb: 1024**2,
gb: 1024**3,
tb: 1024**4,
pb: 1024**5
}

const num = Number(str.match(/\d/).toString())
const type = str.match(/[a-zA-Z]+/).toString().toLowerCase()
return `${str} is ${(num * multiplier[type]).toLocaleString()} bytes!`

}

console.log(giveMeBytes("5mb"));

console.log(giveMeBytes("10TB"));
Might have to finesse it a bit, but it's functional!
Joao
JoaoOPā€¢3y ago
Hey, thanks šŸ™‚ I'm actually looking for an actual npm package that's available and that I can install
13eck
13eckā€¢3y ago
It'sā€¦5 lines of code (plus the multiplier object). Make a file and export giveMeBytes lol. Why the need for an NPM package?
Joao
JoaoOPā€¢3y ago
Yeah I know, but I ended up writing my own code that accounts for both decimal and binary systems (kb and kib), and has checks to esnure the string is valid and whatnot. So I was wondering if there's another library I can compare it to
13eck
13eckā€¢3y ago
Gotcha gotcha
Joao
JoaoOPā€¢3y ago
Not like I don't appreciate the help btw šŸ‘
Want results from more Discord servers?
Add your server