Coder Social home page Coder Social logo

omulti's Introduction

Omulti - Node.js HTTP file uploads

tests

Logo provided by https://www.behance.net/ionutvidican

Getting started

Omulti is a Node.js library that handles HTTP file uploads.

  • Fast
  • Easy to use
  • Written in Typescript
  • It has very few dependencies

To install it run:

npm i omulti

How to use it

Basic usage with Node.js HTTP server

To use it with a Node.js HTTP server simply create a new HTTP server an pass the request object into the Omulti constructor like so:

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    for await (const file of omulti.getFiles()) {
        await file.saveToDisk("/path/where/to/save/file");
    }
});

httpServer.listen(3000);

As you can see the omulti.getFiles() function returns an async generator that allows you to iterate over evey file.

Alternatively, you can also use events if you want:

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    omulti.on("file", (file) => {
        console.log(file.filename);
    });
});

httpServer.listen(3000);

Since Omulti handles multipart/form-data this means that besides files we might also receive input data from form fields.

To get just the fields do:

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    for await (const field of omulti.getFields()) {
        console.log(field.name);
    }
});

httpServer.listen(3000);

To get both files and fields you can use the getAll() method. However you need to distinguish between these two types when working with them:

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    for await (const part of omulti.getAll()) {
        if (part.isFile()) {
            // it's a file
        } else {
            // it's a field
        }
    }
});

httpServer.listen(3000);

As before you can use events here instead, so to get the fields listen on the field event.

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    omulti.on("field", (field) => {
        console.log(file.name);
    });
});

httpServer.listen(3000);

Or to get both files and fields, use the part event:

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);

    omulti.on("part", (part) => {
        if (part.isFile()) {
            // it's a file
        } else {
            // it's a field
        }
    });
});

httpServer.listen(3000);

Options

Omulti allows several options to be passed to the constructor when creating a new instance. All the options are optional.

const omulti = new Omulti(req, {
    maxTotalSize: Number,
    maxFileSize: Number,
    maxFieldSize: Number,
    maxNumberOfFiles: Number,
    maxNumberOfFields: Number,
    maxBufferSize: Number,
});
Option Description Default
maxTotalSize Represents the maximum number of bytes allowed for the entire request Infinity
maxFileSize Represents the maximum number of bytes allowed per file Infinity
maxFieldSize Represents the maximum number of bytes allowed per field Infinity
maxNumberOfFiles Represents the maximum number of files allowed per request Infinity
maxNumberOfFields Represents the maximum number of fields allowed per request Infinity
maxBufferSize Represents the maximum allowed number of bytes to use for the internal buffer. Caution This value is required for Omulti in order to function properly, so it's best not to change it. 10MB

Files and Fields

Properties

A Field has the following properties:

  • name: string | undefined
  • contentType: string | undefined

and a File has the same properties plus:

  • filename: string | undefined

Both entities have a stream property that is a Readable stream.

E.g. you can use this to pipe to a writable stream:

import { createWriteStream } from "fs";
import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req);
    for await (const file of omulti.getFiles()) {
        const writeStream = createWriteStream("/some/path/to/a/dir");
        file.stream.pipe(writeStream);
    }
});

httpServer.listen(3000);

Methods

Field

  • getContents()

File

  • getContents()
  • saveToDisk(path: string)

getContents()

Both entities have a getContents() method that returns a Promise<Buffer> with the entire contents of the Field/File. Be careful when using this, make sure to explicitly set the maxFieldSize and/or the maxFileSize, to prevent the host machine from being starved of memory.

import { createServer } from "http";
import { Omulti } from "omulti";

const httpServer = createServer(async (req, res) => {
    const omulti = new Omulti(req, {
        maxFileSize: 2 * 1024 * 1024, /// max 2MB
    });
    for await (const file of omulti.getFiles()) {
        const contents = (await file.getContents()).toString("utf-8");
        /// do something with the contents
    }
});

httpServer.listen(3000);

saveToDisk(path: string)

The File object also has a saveToDisk('path/to/save/file') method that will save the file to a provided path on the disk.

omulti's People

Contributors

vladvidican avatar

Stargazers

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