formidable
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
Formidable is a Node.js module that specializes in parsing form data, particularly file uploads. This versatile package offers a fast(around 900-2500 mb/sec) and streaming multipart parser that automatically writes file uploads to disk, gives you the option to utilize a Plugins API for custom parsers, maintains a low-memory footprint, and provides very high test coverage.
Using Formidable in your project involves installing it as a dependency through npm and calling its functions in your code. To install the package, navigate to your project root and run npm install formidable
. Here are examples of how to use Formidable with Node.js http module, Express.js, and Koa :
With Node.js http module:
import http from 'node:http';
import formidable, {errors as formidableErrors} from 'formidable';
const server = http.createServer(async (req, res) => {
if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
const form = formidable({});
let fields;
let files;
try {
[fields, files] = await form.parse(req);
} catch (err) {
console.error(err);
res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
res.end(String(err));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ fields, files }, null, 2));
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Upload form');
});
server.listen(8080, () => {
console.log('Server listening on http://localhost:8080/ ...');
});
With Express.js:
import express from 'express';
import formidable from 'formidable';
const app = express();
app.get('/', (req, res) => {
res.send('Upload form');
});
app.post('/api/upload', (req, res, next) => {
const form = formidable({});
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
res.json({ fields, files });
});
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000 ...');
});
With Koa:
import Koa from 'koa';
import formidable from 'formidable';
const app = new Koa();
app.use(async (ctx, next) => {
if (ctx.url === '/api/upload' && ctx.method.toLowerCase() === 'post') {
const form = formidable({});
await new Promise((resolve, reject) => {
form.parse(ctx.req, (err, fields, files) => {
if (err) {
reject(err);
return;
}
ctx.body = { fields, files };
resolve();
});
});
await next();
return;
}
ctx.body = 'Upload form';
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000 ...');
});
Formidable's documentation including detailed API guides, examples, and more, can be found on the official GitHub repository. Here, you can check out usage instructions, learn about the different options and functions provided by the module, and view practical examples of code implementation.