Coder Social home page Coder Social logo

janakhpon / node-formidable Goto Github PK

View Code? Open in Web Editor NEW

This project forked from node-formidable/formidable

0.0 1.0 0.0 2.32 MB

A node.js module for parsing form data, especially file uploads.

License: MIT License

JavaScript 97.82% HTML 2.18%

node-formidable's Introduction

formidable npm version build status chat on gitter MIT license

A Node.js module for parsing form data, especially file uploads.

node formidable logo

Status

This module was initially developed by @felixge for Transloadit, a service focused on uploading and encoding images and videos. It has been battle-tested against hundreds of GBs of file uploads from a large variety of clients and is considered production-ready and is used in production for years.

Currently, we are few maintainers trying to deal with it. :) New maintainers and contributors are always welcome!
Jump on issue #412 if you are interested.

Highlights

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

Installation

npm i formidable

This is a low-level package, and if you're using a high-level framework it may already be included. However, Express v4 does not include any multipart handling, nor does body-parser.

Example

Parse an incoming file upload.

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

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

    form.parse(req, (err, fields, files) => {
      res.writeHead(200, { 'content-type': 'text/plain' });
      res.write('received upload:\n\n');
      res.end(util.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>
  `);
}).listen(8080);

API

Formidable

const form = new Formidable()

Creates a new incoming form.

form.encoding = 'utf-8';

Sets encoding for incoming form fields.

form.uploadDir = "/my/dir";

Sets the directory for placing file uploads in. You can move them later on using fs.rename(). The default is os.tmpdir().

form.keepExtensions = false;

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

form.type

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

form.maxFieldsSize = 20 * 1024 * 1024;

Limits the amount of memory all fields together (except files) can allocate in bytes. If this value is exceeded, an 'error' event is emitted. The default size is 20MB.

form.maxFileSize = 200 * 1024 * 1024;

Limits the size of uploaded file. If this value is exceeded, an 'error' event is emitted. The default size is 200MB.

form.maxFields = 1000;

Limits the number of fields that the querystring parser will decode. Defaults to 1000 (0 for unlimited).

form.hash = false;

If you want checksums calculated for incoming files, set this to either 'sha1' or 'md5'.

form.multiples = false;

If this option is enabled, when you call form.parse, the files argument will contain arrays of files for inputs which submit multiple files using the HTML5 multiple attribute.
Also, the fields argument will contain arrays of values for fields that have names ending with '[]'. That's basic support, better support should be implemented (ref: #386)

form.bytesReceived

The amount of bytes received for this form so far.

form.bytesExpected

The expected number of bytes in this form.

form.parse(request, [cb]);

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

form.parse(req, function(err, fields, files) {
  // ...
});

form.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.

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

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

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

Check the code in this method for further inspiration.

Formidable.File

file.size = 0

The size of the uploaded file in bytes. If the file is still being uploaded (see 'fileBegin' event), this property says how many bytes of the file have been written to disk yet.

file.path = null

The path this file is being written to. You can modify this in the 'fileBegin' event in case you are unhappy with the way formidable generates a temporary path for your files.

file.name = null

The name this file had according to the uploading client.

file.type = null

The mime type of this file, according to the uploading client.

file.lastModifiedDate = null

A date object (or null) containing the time this file was last written to. Mostly here for compatibility with the W3C File API Draft.

file.hash = null

If hash calculation was set, you can read the hex digest out of this var.

Formidable.File#toJSON()

This method returns a JSON-representation of the file, allowing you to JSON.stringify() the file which is useful for logging and responding to requests.

Events

'progress'

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

form.on('progress', function(bytesReceived, bytesExpected) {
});

'field'

Emitted whenever a field / value pair has been received.

form.on('field', function(name, value) {
});

'fileBegin'

Emitted whenever a new file is detected in the upload stream. Use this event if you want to stream the file to somewhere else while buffering the upload on the file system.

form.on('fileBegin', function(name, file) {
});

'file'

Emitted whenever a field / file pair has been received. file is an instance of File.

form.on('file', function(name, file) {
});

'error'

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.

form.on('error', function(err) {
});

'aborted'

Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. After this event is emitted, an error event will follow. In the future there will be a separate 'timeout' event (needs a change in the node core).

form.on('aborted', function() {
});
'end'
form.on('end', function() {
});

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.

Ports

Credits

node-formidable's People

Contributors

aheckmann avatar andrewrk avatar bengourley avatar btrask avatar christian-fei avatar egirshov avatar elmerbulthuis avatar felixge avatar grossacasac avatar jimbly avatar kethinov avatar kornelski avatar mattrobenolt avatar mdionisio avatar mikefrey avatar mkdynamic avatar nicholaiii avatar nickstamas avatar nshahri avatar orangedog avatar rkusa avatar sreuter avatar svnlto avatar taddei avatar tanukisharp avatar tim-smart avatar tj avatar tojocky avatar tunnckocore avatar vilcans avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.