Coder Social home page Coder Social logo

amit-a / formidable-serverless Goto Github PK

View Code? Open in Web Editor NEW
34.0 1.0 2.0 85 KB

Enables use of formidable (node.js module for parsing form data, especially file uploads) in serverless environments.

Home Page: https://www.npmjs.com/package/formidable-serverless

License: MIT License

JavaScript 100.00%
serverless nodejs-modules formidable lambda cloudfunctions

formidable-serverless's Introduction

formidable-serverless

npm version

Purpose

This module is a variant of formidable with tweaks to enable use in serverless environments (AWS Lambda, Firebase/Google Cloud Functions, etc.) and environments where the request has already been processed (e.g. by bodyparser).

The functionality and usage/API are identical to formidable (documentation cloned below).

Status

Sponsored and maintained by the folks at testmail.app

How it works

The preprocessing by bodyparsers built-in to serverless environments breaks formidable's parse handlers and causes "Request Aborted" errors. This module imports formidable as a dependency and modifies the handlers to support preprocessed request bodies.

This module can also be used in non-serverless environments (usage and API are identical), but it may be a version or two behind. This package is focused on serverless - if you have issues with formidable itself, please open them in the formidable repo.

Formidable

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

Formidable was developed for Transloadit, a service focused on uploading and encoding images and videos. It has been battle-tested against hundreds of GB of file uploads from a large variety of clients and is considered production-ready.

Features

  • 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 install --save formidable-serverless

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 formidable = require('formidable-serverless');
const http = require('http');
const util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    const 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(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.IncomingForm

var form = new formidable.IncomingForm()

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.

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 and formidable-serverless are licensed under the MIT license.

formidable-serverless's People

Contributors

amit-a avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

formidable-serverless's Issues

TypeError: this._parser.write is not a function

I like formidable-serverless, it really solved my pain with Firebase functions.
It is used as following:

const formidable = require("formidable-serverless");

function getBodyFields(req) {
  var form = new formidable.IncomingForm();
  return new Promise((resolve, reject) => {
    form.parse(req, (err, fields) => {
      if (err) reject(err);
      else if (Object.keys(fields).length === 0) reject(new Error("No data to upload."));
      else resolve(fields);
    });
  });
}

api.post(apiPath, async (req, res) => {
  try {
    const { base64, width, height, ext } = await getBodyFields(req);
  } catch (error) {
    console.error(error);
    res.status(500).send(error);
  }
});

Having sent an empty request without any field and file the unhandled error happened:

TypeError: this._parser.write is not a function
at IncomingForm.write (/functions/node_modules/formidable/lib/incoming_form.js:159:34)
at IncomingForm.formidable.IncomingForm.parse (/functions/node_modules/formidable-serverless/lib/index.js:58:10)
at Promise (/functions/api.js:114:10)
at new Promise ()
at getBodyFields (/functions/api.js:113:10)
at api.post (/functions/api.js:31:50)
at Layer.handle [as handle_request] (/functions/node_modules/express/lib/router/layer.js:95:5)
at next (/functions/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/functions/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/functions/node_modules/express/lib/router/layer.js:95:5)

"Unhandled" means that error was not cought with neither
if (err) reject(err);
nor
if (Object.keys(fields).length === 0) reject(new Error("No data to upload."));

It would be good to catch this error in callback function as err.

Thank you!

"TypeError: req.on is not a function",

Hi, @Amit-A ,

AWS lambda is throwing:

> 2024-02-21T08:21:47.729Z	d74793a1-1596-4182-9ce5-6eb0370f8941	ERROR	Invoke Error 	
> {
>     "errorType": "TypeError",
>     "errorMessage": "req.on is not a function",
>     "stack": [
>         "TypeError: req.on is not a function",
>         "    at formidable.IncomingForm.parse (/var/task/node_modules/formidable-serverless/lib/index.js:39:7)",
>         "    at response.statusCode (/var/task/index.js:89:12)",
>         "    at new Promise (<anonymous>)",
>         "    at exports.handler (/var/task/index.js:88:12)"
>     ]
> }

I have a really plain lambda so I’m not sure what I’m missing.

My AWS lambda config:

Compatible architectures - Both:
• x86_64
• arm64

Compatible runtimes:
• nodejs 20.x

console.log('Node version is: ' + process.version);
console.log(process.versions);

Shows in CloudWatch:

Node version is: v20.11.0
{
node: '20.11.0',
acorn: '8.11.2',
ada: '2.7.4',
ares: '1.20.1',
base64: '0.5.1',
brotli: '1.0.9',
cjs_module_lexer: '1.2.2',
cldr: '43.1',
icu: '73.2',
llhttp: '8.1.1',
modules: '115',
napi: '9',
nghttp2: '1.58.0',
openssl: '3.1.4',
simdutf: '4.0.4',
tz: '2023c',
undici: '5.27.2',
unicode: '15.0',
uv: '1.46.0',
uvwasi: '0.0.19',
v8: '11.3.244.8-node.17',
zlib: '1.2.13.1-motley-5daffc7'
}

Here is my index.js:

console.log('Node version is: ' + process.version);
console.log(process.versions);

const isCustom = require('/opt/nodejs/myCustom');

const formidable = require('formidable-serverless');
const http = require('http');
const util = require('util');


const { S3Client } = require("@aws-sdk/client-s3");
const s3 = new S3Client({ region: "us-east-1" });


exports.handler = async(event) => {
    const res = await isCustom.handler(event);
    if (!res.isValid) { return res.failed; }



    const form = new formidable.IncomingForm();

    return new Promise((resolve, reject) => {
      form.parse(event, (err, fields, files) => {
        if(err) return reject(err);

        console.log(fields);  
        console.log(files);  
  
        resolve({status: 'ok'});
      });
    });
  


    return res.def; 
};

I have an easily reproducible setup:
• Windows 10 with VS Code.
• Just installed node 20.11.1 LTS from nodejs.org using the big button which downloads:
node-v20.11.1-x64.msi
• In my VS Code terminal:
npm install npm@latest -g
• So now
npm -v
Shows version: 10.4.0
node -v
Shows version: v20.11.1

  1. Created my folder "c:\git\lmbd-202-api" and added in my "index.js" as shown above.
  2. In VS Code: File, Open [that] folder.
  3. In VS Code: Terminal, New terminal and type:
    npm init -y
  4. Then type:
    npm install formidable-serverless

The output was:
npm WARN deprecated [email protected]: Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau

Is there a npm command to just upgrade the parts of formidable that are needed (like your install only pulls 43k) or do I have to pull the entire 400k? Note, I still received the same error after downloading all of it.
npm install formidable@v3

  1. Selected all the files in my "lmbd-202-api" folder, right mouse click: Send to: Compressed zip folder, and name it "lmbd-202-api.zip."
  2. In the AWS Lambda console, on the “Code source” page, click Upload from, .zip file. Select the lmbd-202-api.zip. Note "lmbd-202-api" is also the exact name of my Lambda function.
  3. In the AWS Lambda console, add a space after any semicolon so the Deploy button becomes active; Then click it.
  4. Hitting the end point with a Postman PUT with multipart Form-Data that contains a 1k json file and two 50k images throws the 500 level error.

Note, my CloudFront origin is passing the request to my API Gateway which has Lambda Proxy Integration on and is in turn passing the request to my Lambda. Note, I logged the entire event to CloudWatch and the last line in the event is: isBase64Encoded: false.

Thank you

Types definitions

2022-01-27 12 41 11

In the docs it says it uses the same API as formidable. There's an easy and straightforward to extend the type definitions from formidable to formidable-serverless?

I was thinking in installing like this:

npm i --save formidable-serverless
i --save-dev @types/formidable

And somehow instruct Node to use formidable's types for formidable-serverless.

Failed to upload image to S3 bucket.

I am trying to upload image to s3 bucket with aws-sdk and formidable-serverless, but I got error when uploading the image from frontend, here is my code in use:

const aws = require("aws-sdk")
const uuid = require("uuid")
import formidable from "formidable-serverless"

const Bucket = "bucket"

const s3 = new aws.S3({
	accessKeyId: "xxx",
	secretAccessKey: "xxx",
	region: "xxx",
	endpoint: "s3.xxx",
	signatureVersion: "v4",
})

export default async (req, res) => {
	const form = new formidable.IncomingForm()
	form.parse(req, (err, fields, files) => {
		const file = {
			Bucket: Bucket,
			Key: uuid.v4() + " - " + files.file.name,
			Body: files.file,
			ContentType: files.file.type,
		}
		console.log(file)
		s3.putObject(file, function (err, data) {
			if (err) console.log("Error: " + err)
			else res.send(data)
		})
	})
}

Here is the error I can't handle with:

NetworkingError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received an instance of File

console.log(file) shows:

{
  Bucket: 'bucket',
  Key: 'd5f53b62-dbc3-4206-99c4-482970d0f16a - test.png',
  Body: File {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    size: 89865,
    path: '/var/folders/7_/8fbg7my57lx3z46ccfwjddj80000gn/T/upload_3463316247a7d167eadba05a7c0d01b3',
    name: 'test.png',
    type: 'image/png',
    hash: null,
    lastModifiedDate: 2021-04-22T14:20:11.945Z,
    _writeStream: WriteStream {
      _writableState: [WritableState],
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      path: '/var/folders/7_/8fbg7my57lx3z46ccfwjddj80000gn/T/upload_3463316247a7d167eadba05a7c0d01b3',
      fd: 57,
      flags: 'w',
      mode: 438,
      start: undefined,
      autoClose: true,
      pos: undefined,
      bytesWritten: 89865,
      closed: false,
      [Symbol(kFs)]: [Object],
      [Symbol(kCapture)]: false,
      [Symbol(kIsPerformingIO)]: false
    },
    [Symbol(kCapture)]: false
  },
  ContentType: 'image/png'
}

When I set Body to Body: toString(files.file) then I can upload but the uploaded image can not be opened.

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.