What is @hapi/ammo?
@hapi/ammo is a utility library for HTTP payload processing, specifically designed to handle HTTP payload ranges. It is part of the hapi ecosystem and is used to parse and validate HTTP Range headers, which are often used for partial content delivery.
What are @hapi/ammo's main functionalities?
Range Parsing
This feature allows you to parse the 'Range' HTTP header and determine the byte ranges requested by the client. The `Ammo.header` function takes the range header and the total length of the resource, returning an array of ranges.
const Ammo = require('@hapi/ammo');
const rangeHeader = 'bytes=0-4,9-15';
const length = 20;
const ranges = Ammo.header(rangeHeader, length);
console.log(ranges);
Range Validation
This feature validates the parsed ranges to ensure they are within the bounds of the resource length. If the ranges are valid, it returns an array of ranges; otherwise, it returns null.
const Ammo = require('@hapi/ammo');
const rangeHeader = 'bytes=0-4,9-15';
const length = 20;
const ranges = Ammo.header(rangeHeader, length);
if (ranges) {
console.log('Valid ranges:', ranges);
} else {
console.log('Invalid range header');
}
Other packages similar to @hapi/ammo
range-parser
The 'range-parser' package is a utility for parsing HTTP Range headers. It provides similar functionality to @hapi/ammo by parsing range headers and returning the requested ranges. However, it is a more lightweight and standalone package compared to @hapi/ammo, which is part of the larger hapi ecosystem.
ammo
HTTP Range processing utilities.
Usage
const range = Ammo.header('bytes=1-5', 10);
const range = Ammo.header('bytes=1-5,7-10', 10);
const range = Ammo.header('bytes=1000-4000', 5000);
const stream = new Ammo.Stream(range[0]);
const buffer = await Wreck.read(source.pipe(stream));
API
Parses the range from a HTTP header.
header
- A string in the form of bytes=from-to
, where from
and to
are
integers specifying the range. Both are optional. Multiple ranges can be passed
as a comma delimited list.length
- A positive integer specifying the maximum length the range can
cover. If a to
value passed in the header
string is greater than length
,
the to
value is set as length - 1
.
Returns an array of objects with the properties from
and to
, which specify
the beginning and ending of the range. Overlapping ranges are combined into one
object. Returns null
for invalid input.
new Ammo.Stream(range)
Creates a Transform Stream
that extracts
the portion of a piped in stream within range
.
range
- an object with the properties from
and to
that specify the range
of the piped in stream to read. Objects returned by Ammo.header
can be passed
into range
.