Socket
Socket
Sign inDemoInstall

formidable

Package Overview
Dependencies
1
Maintainers
0
Versions
78
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    formidable


Version published
Maintainers
0
Install size
82.4 kB
Created

Package description

What is formidable?

The formidable npm package is a Node.js module for parsing form data, especially file uploads. It can handle multipart/form-data, which is used for uploading files through forms.

What are formidable's main functionalities?

File Upload

This code creates an HTTP server that listens for POST requests on the '/upload' path. It uses formidable to parse the incoming form data and handle file uploads.

const formidable = require('formidable');
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
      if (err) {
        res.writeHead(500, { 'content-type': 'text/plain' });
        res.end('Error parsing the files');
        return;
      }
      res.writeHead(200, { 'content-type': 'text/plain' });
      res.write('Files uploaded successfully:\n');
      res.end(JSON.stringify(files, null, 2));
    });
  }
}).listen(8080);

Form Field Parsing

This code snippet demonstrates how to use formidable to parse regular form fields (text inputs, selects, etc.) in addition to file uploads.

const formidable = require('formidable');
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/submit' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
      if (err) {
        res.writeHead(500, { 'content-type': 'text/plain' });
        res.end('Error parsing the form fields');
        return;
      }
      res.writeHead(200, { 'content-type': 'text/plain' });
      res.write('Form fields submitted:\n');
      res.end(JSON.stringify(fields, null, 2));
    });
  }
}).listen(8080);

File Upload Progress

This example shows how to track the progress of a file upload using formidable's 'progress' event, which provides the bytes received and the total bytes expected.

const formidable = require('formidable');
const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();

    form.on('progress', (bytesReceived, bytesExpected) => {
      console.log(`Progress: ${bytesReceived}/${bytesExpected}`);
    });

    form.parse(req, (err, fields, files) => {
      // Handle file upload and response
    });
  }
}).listen(8080);

Other packages similar to formidable

Readme

Source

Formidable

Purpose

A node.js module for dealing with web forms.

Features

  • Fast (~500mb/sec), non-buffering multipart parser
  • Automatically writing file uploads to disk
  • Low memory footprint
  • Graceful error handling
  • Very high test coverage

Todo

  • Implement QuerystringParser the same way as MultipartParser

Installation

Via npm:

npm install formidable@latest

Manually:

git clone git://github.com/felixge/node-formidable.git formidable
vim my.js
# var formidable = require('./formidable');

Note: Formidable requires gently to run the unit tests, but you won't need it for just using the library.

Example

Parse an incoming file upload.

var formidable = require('formidable')
  , http = require('http')
  , sys = require('sys');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(sys.inspect({fields: fields, files: files}));
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end
    ( '<form action="/upload" enctype="multipart/form-data" method="post">'
    + '<input type="text" name="title"><br>'
    + '<input type="file" name="upload" multiple="multiple"><br>'
    + '<input type="submit" value="Upload">'
    + '</form>'
    );
});

API

formdiable.IncomingForm

new formdiable.IncomingForm()

Creates a new incoming form.

incomingForm.encoding = 'utf-8'

The encoding to use for incoming form fields.

incomingForm.uploadDir = '/tmp'

The directory for placing file uploads in. You can later on move them using fs.rename().

incomingForm.keepExtensions = false

If you want the files written to incomingForm.uploadDir to include the extensions of the original files, set this property to true.

incomingForm.type

Either 'multipart' or 'urlencoded' depending on the incoming request.

incomingForm.maxFieldSize = 2 * 1024 * 1024

Limits the amount of memory a field (not file) can allocate in bytes. I this value is exceeded, an 'error' event is emitted. The default size is 2MB.

incomingForm.bytesReceived

The amount of bytes received for this form so far.

incomingForm.bytesExpected

The expected number of bytes in this form.

incomingForm.parse(request, [cb])

Parses an incoming node.js request containing form data. If cb is provided, all fields an files are collected and passed to the callback:

incomingForm.parse(req, function(err, fields, files) {
  // ...
});
incomingForm.onPart(part)

You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any 'field' / 'file' events processing which would occur otherwise, making you fully responsible for handling the processing.

incomingForm.onPart = function(part) {
  part.addListener('data', function() {
    // ...
  });
}

If you want to use formidable to only handle certain parts for you, you can do so:

incomingForm.onPart = function(part) {
  if (!part.filename) {
    // let formidable handle all non-file parts
    incomingForm.handlePart(part);
  }
}

Check the code in this method for further inspiration.

Event: 'progress' (bytesReceived, bytesExpected)

Emitted after each incoming chunk of data that has been parsed. Can be used to roll your own progress bar.

Event: 'field' (name, value)

Emitted whenever a field / value pair has been received.

Event: 'file' (name, file)

Emitted whenever a field / file pair has been received. file is a JS object with the following properties:

{ path: 'the path in the uploadDir this file was written to'
, filename: 'the name this file had on the computer of the uploader'
, mime: 'the mime type specified by the user agent of the uploader'
}
Event: 'error' (err)

Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call request.resume() if you want the request to continue firing 'data' events.

Event: 'end' ()

Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response.

License

Formidable is licensed under the MIT license.

Credits

FAQs

Last updated on 18 Jan 2011

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc