All Projects → m4nuC → Async Busboy

m4nuC / Async Busboy

Licence: mit
Promise based multipart form parser for KoaJS

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Async Busboy

Datakernel
Alternative Java platform, built from the ground up - with its own async I/O core and DI. Ultra high-performance, simple and minimalistic - redefines server-side programming, web-development and highload!
Stars: ✭ 87 (-45.28%)
Mutual labels:  async, promise
Bach
Compose your async functions with elegance.
Stars: ✭ 117 (-26.42%)
Mutual labels:  async, promise
Taskorama
⚙ A Task/Future data type for JavaScript
Stars: ✭ 90 (-43.4%)
Mutual labels:  async, promise
Flowa
🔥Service level control flow for Node.js
Stars: ✭ 66 (-58.49%)
Mutual labels:  async, promise
Sieppari
Small, fast, and complete interceptor library for Clojure/Script
Stars: ✭ 133 (-16.35%)
Mutual labels:  async, promise
Emittery
Simple and modern async event emitter
Stars: ✭ 1,146 (+620.75%)
Mutual labels:  async, promise
Jdeferred
Java Deferred/Promise library similar to JQuery.
Stars: ✭ 1,483 (+832.7%)
Mutual labels:  async, promise
Emacs Async Await
Async/Await for Emacs
Stars: ✭ 47 (-70.44%)
Mutual labels:  async, promise
Rubico
[a]synchronous functional programming
Stars: ✭ 133 (-16.35%)
Mutual labels:  async, promise
Kitchen Async
A Promise library for ClojureScript, or a poor man's core.async
Stars: ✭ 128 (-19.5%)
Mutual labels:  async, promise
Promised Pipe
A ramda.pipe-like utility that handles promises internally with zero dependencies
Stars: ✭ 64 (-59.75%)
Mutual labels:  async, promise
Unityfx.async
Asynchronous operations (promises) for Unity3d.
Stars: ✭ 143 (-10.06%)
Mutual labels:  async, promise
Download
Download and extract files
Stars: ✭ 1,064 (+569.18%)
Mutual labels:  async, promise
Write
Write data to the file system, creating any intermediate directories if they don't already exist. Used by flat-cache and many others!
Stars: ✭ 68 (-57.23%)
Mutual labels:  async, promise
Before After Hook
wrap methods with before/after hooks
Stars: ✭ 49 (-69.18%)
Mutual labels:  async, promise
Tedis
redis client with typescript and esnext for nodejs
Stars: ✭ 109 (-31.45%)
Mutual labels:  async, promise
Breeze
Javascript async flow control manager
Stars: ✭ 38 (-76.1%)
Mutual labels:  async, promise
Node Qiniu Sdk
七牛云SDK,使用 ES2017 async functions 来操作七牛云,接口名称与官方接口对应,轻松上手,文档齐全
Stars: ✭ 44 (-72.33%)
Mutual labels:  async, promise
Tas
Make it easy to develop large, complex Node.js app.
Stars: ✭ 128 (-19.5%)
Mutual labels:  async, promise
Functional Promises
Write code like a story w/ a powerful Fluent (function chaining) API
Stars: ✭ 141 (-11.32%)
Mutual labels:  async, promise

Promise Based Multipart Form Parser

NPM version build status Test coverage npm download

The typical use case for this library is when handling forms that contain file upload field(s) mixed with other inputs. Parsing logic relies on busboy. Designed for use with Koa2 and Async/Await.

Examples

Async/Await (using temp files)

import asyncBusboy from 'async-busboy';

// Koa 2 middleware
async function(ctx, next) {
  const {files, fields} = await asyncBusboy(ctx.req);

  // Make some validation on the fields before upload to S3
  if ( checkFiles(fields) ) {
    files.map(uploadFilesToS3)
  } else {
    return 'error';
  }
}

Async/Await (using custom onFile handler, i.e. no temp files)

import asyncBusboy from 'async-busboy';

// Koa 2 middleware
async function(ctx, next) {
  const { fields } = await asyncBusboy(ctx.req, {
    onFile: function(fieldname, file, filename, encoding, mimetype) {
      uploadFilesToS3(file);
    }
  });

  // Do validation, but files are already uploading...
  if ( !checkFiles(fields) ) {
    return 'error';
  }
}

ES5 with promise (using temp files)

var asyncBusboy = require('async-busboy');

function(someHTTPRequest) {
  asyncBusboy(someHTTPRequest).then(function(formData) {
    // do something with formData.files
    // do someting with formData.fields
  });
}

Async API using temp files

The request streams are first written to temporary files using os.tmpdir(). File read streams associated with the temporary files are returned from the call to async-busboy. When the consumer has drained the file read streams, the files will be automatically removed, otherwise the host OS should take care of the cleaning process.

Async API using custom onFile handler

If a custom onFile handler is specified in the options to async-busboy it will only resolve an object containing fields, but instead no temporary files needs to be created since the file stream is directly passed to the application. Note that all file streams need to be consumed for async-busboy to resolve due to the implementation of busboy. If you don't care about a received file stream, simply call stream.resume() to discard the content.

Working with nested inputs and objects

Make sure to serialize objects before sending them as formData. i.e:

// Given an object that represent the form data:
{
  'field1': 'value',
  'objectField': {
    'key': 'anotherValue'
  },
  'arrayField': ['a', 'b']
  //...
};

Should be sent as:

// -> field1[value]
// -> objectField[key][anotherKey]
// -> arrayField[0]['a']
// -> arrayField[1]['b']
// .....

Here is a function that can take care of this process

const serializeFormData = (obj, formDataObj, namespace = null) => {
  var formDataObj = formDataObj || {};
  var formKey;
  for(var property in obj) {
    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      var value = obj[property];
      if(typeof value === 'object' && !(value instanceof File) && !(value instanceof Date)) {
          serializeFormData(value, formDataObj, formKey);
      } else if(value instanceof Date) {
        formDataObj[formKey] = value.toISOString();
      } else {
        formDataObj[formKey] = value;
      }
    }
  }
  return formDataObj;
};

// -->

Try it on your local

If you want to run some test locally, clone this repo, then run: node examples/index.js From there you can use something like Postman to send POST request to localhost:8080. Note: When using Postman make sure to not send a Content-Type header, if it's filed by default, just delete it. (This is to let the boudary header be generated automaticaly)

Use cases:

  • Form sending only octet-stream (files)

  • Form sending file octet-stream (files) and input fields. a. File and fields are processed has they arrive. Their order do not matter. b. Fields must be processed (for example validated) before processing the files.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].