Utility to parse a string bytes to bytes and vice-versa
The bytes package is a lightweight utility that solves a common problem in JavaScript applications: converting between human-readable byte values (like "1KB" or "2.5MB") and their numeric representations in bytes. With over 90 million weekly downloads, it's a foundational dependency in the Node.js ecosystem, particularly for web frameworks like Express that need to parse Content-Length headers and format file sizes.
The package provides a bidirectional API that automatically detects whether you're parsing a string to a number or formatting a number to a string. It handles the complexity of unit conversion (KB, MB, GB, TB, PB) and supports both decimal (1000-based) and binary (1024-based) calculations. The implementation is deliberately minimal—no dependencies, small footprint, and a straightforward API surface.
Developers building HTTP servers, file upload systems, storage management tools, or CLI utilities commonly reach for this package to avoid reimplementing byte conversion logic. It's particularly valuable in middleware that validates request sizes, logging systems that format bandwidth metrics, and dashboard applications displaying storage statistics. The package's reliability and ubiquity make it a de facto standard for byte manipulation in the JavaScript ecosystem.
Under the hood, bytes uses regular expressions to parse unit suffixes and applies appropriate multiplication factors. It handles edge cases like invalid input gracefully (returning null instead of throwing), supports customizable decimal precision, and allows localization through separators. The API is designed for both convenience (single function) and explicitness (separate parse/format methods).
import bytes from 'bytes';
// Parse human-readable strings to numeric bytes
const uploadLimit = bytes('10MB'); // 10485760
const configLimit = bytes.parse('50mb'); // 52428800 (case-insensitive)
// Format numeric bytes to readable strings
const fileSize = bytes(1536000); // '1.46MB'
const formatted = bytes.format(1024 * 1024, {
decimalPlaces: 0,
unitSeparator: ' '
}); // '1 MB'
// Real-world Express middleware example
function validateRequestSize(maxSize) {
const limitBytes = bytes(maxSize);
return (req, res, next) => {
const contentLength = parseInt(req.headers['content-length'], 10);
if (contentLength > limitBytes) {
return res.status(413).json({
error: 'Payload too large',
limit: bytes(limitBytes),
received: bytes(contentLength)
});
}
next();
};
}
// Usage
app.post('/upload', validateRequestSize('5MB'), uploadHandler);
// Format with thousands separator for logs
const transferred = 1234567890;
console.log(`Transferred: ${bytes.format(transferred, {
thousandsSeparator: ',',
decimalPlaces: 2
})}`); // 'Transferred: 1.15GB'HTTP Request Validation: Express and Koa applications use bytes to parse Content-Length headers and enforce request size limits. Middleware can reject uploads exceeding a configured threshold by comparing parsed byte values from config strings like "10MB" against actual request sizes.
File System Operations: CLI tools and file management applications format file sizes for human consumption. Instead of displaying "1048576 bytes", tools use bytes to render "1MB" in directory listings, progress bars, and storage dashboards.
Configuration Management: Applications store size limits in configuration files as readable strings ("UPLOAD_LIMIT=50MB") and parse them at runtime. This improves maintainability compared to hardcoded numeric values that require mental conversion.
Logging and Monitoring: Backend services format bandwidth usage, memory consumption, and database sizes in log output. Monitoring dashboards convert numeric metrics to human-readable strings for graphs and alerts, making operational data more accessible.
API Response Formatting: REST APIs return file metadata with formatted size fields. Instead of forcing clients to implement formatting logic, servers use bytes to provide consistent, readable size representations across endpoints.
npm install bytespnpm add bytesbun add bytes