What is @hapi/pez?
@hapi/pez is a streaming parser for multipart payloads, which is commonly used in handling file uploads in web applications. It is part of the hapi ecosystem and provides a robust solution for parsing multipart/form-data content types.
What are @hapi/pez's main functionalities?
Multipart Parser
This code demonstrates how to use @hapi/pez to parse a multipart payload. The parser is configured with a boundary string and listens for 'part' events, which represent individual parts of the multipart payload. Each part is then piped to the standard output.
const Pez = require('@hapi/pez');
const internals = {};
internals.multipart = new Pez.Multipart({
boundary: '----WebKitFormBoundaryE19zNvXGzXaLvS5C'
});
internals.multipart.on('part', (part) => {
part.pipe(process.stdout);
});
internals.multipart.write('------WebKitFormBoundaryE19zNvXGzXaLvS5C\r\n');
internals.multipart.write('Content-Disposition: form-data; name="file"; filename="example.txt"\r\n');
internals.multipart.write('Content-Type: text/plain\r\n\r\n');
internals.multipart.write('Hello World\r\n');
internals.multipart.write('------WebKitFormBoundaryE19zNvXGzXaLvS5C--\r\n');
internals.multipart.end();
File Upload Handling
This example shows how to handle file uploads using @hapi/pez. Each part of the multipart payload is written to a file using a writable stream. The filename is extracted from the part's metadata.
const Pez = require('@hapi/pez');
const fs = require('fs');
const internals = {};
internals.multipart = new Pez.Multipart({
boundary: '----WebKitFormBoundaryE19zNvXGzXaLvS5C'
});
internals.multipart.on('part', (part) => {
const fileStream = fs.createWriteStream(part.filename);
part.pipe(fileStream);
});
internals.multipart.write('------WebKitFormBoundaryE19zNvXGzXaLvS5C\r\n');
internals.multipart.write('Content-Disposition: form-data; name="file"; filename="example.txt"\r\n');
internals.multipart.write('Content-Type: text/plain\r\n\r\n');
internals.multipart.write('Hello World\r\n');
internals.multipart.write('------WebKitFormBoundaryE19zNvXGzXaLvS5C--\r\n');
internals.multipart.end();
Other packages similar to @hapi/pez
busboy
Busboy is a fast and low-level streaming parser for HTML form data, especially file uploads. It is similar to @hapi/pez in that it handles multipart/form-data, but it is often used with the express framework and provides a more minimalistic API.
multer
Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It is built on top of busboy and provides a higher-level API compared to @hapi/pez, making it easier to integrate with Express applications.
formidable
Formidable is a Node.js module for parsing form data, especially file uploads. It is similar to @hapi/pez in functionality but offers a more comprehensive API for handling various types of form data, including multipart and urlencoded forms.