Introduction to Busboy
Busboy is a Node.js module for handling HTML form file uploads. It is a lightweight and efficient middleware that makes file uploading in Node.js applications straightforward. In this blog post, we’ll explore Busboy and provide dozens of useful API explanations with code snippets.
Installing Busboy
npm install busboy
Initializing Busboy
First, set up a basic Node.js server and initialize Busboy:
const http = require('http'); const Busboy = require('busboy'); const server = http.createServer((req, res) => { if (req.method === 'POST') { const busboy = new Busboy({ headers: req.headers }); // Busboy code will go here } else { res.writeHead(404); res.end(); } }); server.listen(8000, () => { console.log('Server listening on http://localhost:8000'); });
Handling File Uploads
You can add event listeners to handle different parts of the upload:
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`); file.on('data', (data) => { console.log(`File [${fieldname}] got ${data.length} bytes`); }); file.on('end', () => { console.log(`File [${fieldname}] Finished`); }); }); busboy.on('finish', () => { res.writeHead(200, { 'Connection': 'close' }); res.end("That's all folks!"); }); req.pipe(busboy);
Handling Form Fields
Busboy also allows you to handle regular form fields:
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { console.log(`Field [${fieldname}]: value: ${val}`); });
Complete App Example
Here’s a complete example of a simple file upload server:
const http = require('http'); const Busboy = require('busboy'); const server = http.createServer((req, res) => { if (req.method === 'POST') { const busboy = new Busboy({ headers: req.headers }); busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`); file.on('data', (data) => { console.log(`File [${fieldname}] got ${data.length} bytes`); }); file.on('end', () => { console.log(`File [${fieldname}] Finished`); }); }); busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { console.log(`Field [${fieldname}]: value: ${val}`); }); busboy.on('finish', () => { res.writeHead(200, { 'Connection': 'close' }); res.end("That's all folks!"); }); req.pipe(busboy); } else { res.writeHead(404); res.end(); } }); server.listen(8000, () => { console.log('Server listening on http://localhost:8000'); });
By using Busboy, you can effectively handle file uploads and form data in your Node.js applications with ease.
Hash: 2a9af83d983d8dff397fefc03ef7cb874ecf6dd112b9c48e261c05105f224020