API reference › @evolu/common › Bytes › ByteLengthFromString
const ByteLengthFromString: transform(
"ByteLengthFromString",
String,
ByteLength,
{
from: (value: string): Result<number, ByteLengthFromStringError> => {
if (ByteSizeLiteral.is(value)) return ok(byteSizeToByteLength(value));
if (/^\d+$/u.test(value)) {
const number = Number(value);
if (Number.isSafeInteger(number)) return ok(number);
}
return err({ type: "ByteLengthFromString", value });
},
to: (value: ByteLength) => globalThis.String(value),
},
formatByteLengthFromStringError,
);
Defined in: packages/common/src/Bytes.ts:2186
Transforms a number of bytes or a ByteSizeLiteral in text into a ByteLength.
This is useful for inputs that carry sizes as text, such as environment
variables and configuration files, where "10MiB" reads better than
"10485760". Encoding produces the number of bytes.
Example
import {
assertEqual,
assertErr,
assertOk,
ByteLengthFromString,
} from "@evolu/common";
assertOk(ByteLengthFromString.fromUnknown("10MiB"), 10485760);
assertOk(ByteLengthFromString.fromUnknown("1048576"), 1048576);
assertEqual(
ByteLengthFromString.to(ByteLengthFromString.orThrow("1KiB")),
"1024",
);
const invalid = ByteLengthFromString.fromUnknown("10MB");
assertErr(invalid, { type: "ByteLengthFromString", value: "10MB" });
assertEqual(
ByteLengthFromString.formatError(invalid.error),
'The value "10MB" is not a byte length. Use a number of bytes or a literal such as 10MiB.',
);