GithubHelp home page GithubHelp logo

karladler / async-busboy Goto Github PK

View Code? Open in Web Editor NEW

This project forked from m4nuc/async-busboy

0.0 2.0 0.0 35 KB

Promise based multipart form parser for KoaJS

License: MIT License

JavaScript 100.00%

async-busboy's Introduction

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

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';
  }
}

ES5 with promise

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

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

As of today there is no support for directly piping of the request stream into a consumer. The files are first written to disk using os.tmpdir(). When the consumer stream drained the request stream, files will be automatically removed, otherwise the host OS should take care of the cleaning process.

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 localy, 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.

async-busboy's People

Contributors

christensson avatar dominhhai avatar fireyy avatar jd-robbs avatar loborobo avatar m4nuc avatar octet-stream avatar

Watchers

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