npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

busboy-upload

v2.2.0

Published

This express middleware is handling fileuploads on top of connect-busboy.

Downloads

11

Readme

busboy-upload

This express middleware is handling fileuploads on top of connect-busboy. It provides an simple solution to deal with large files.

$ npm install busboy-upload

Content

  • Usage
  • API Response
  • Set up the express middleware
  • Informations about the uploaded file
  • Error Handling
  • Test your code

Usage

First of all, we need to define the callbacks to get informations about the upload

/**
 * Is fired when file has been successfully uploaded
 * @param {Object} fileInfo 
 */
const success = (file) => {

    console.log(file.stats); // { total: 20, error: 10, success: 10 }
    console.log(file.files); // Array of all files
    console.log(file.duration); //file upload duration in ms
    
}

const config = {
    uploadPath: __dirname + '/uploads/',
    uploadName: Date.now(),
    maxSize: 100000,
    mimeTypes: ['image/jpeg'], // Take a look into all aviable mime types here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
    maxsize: 100000, // In bytes
    filter: (file, deny) => {
        if(file.originalFile.filename == 'test.jpesg') return deny('INVALID_BIT_AMOUNT'); // Method needs to be returned!
    },
    onlyRead: true // Only reads the incoming form-data, appends an parameter chunks to file as a Buffer of the file content
}

Note: If you do not want to apply a filter, just leave the config parameter blanc.

The parameter file in filter will have the format like this.

API Response

{
  stats: { total: 20, error: 10, success: 10 },
  files: [],
  duration: 1041 //in ms
}

Set up the middleware

The API needs to be included in one of the express Routers:

const busboy = require('busboy');
const fileUpload = require('busboy-upload');

app.use(busboy({ immediate: true }));

app.use('/upload', (req, res) => {

  // Callbacks from above
  
  fileUpload(req, success, config);
});

File Object

File has been successfully uploaded:

{
  errors: [],
  originalFile: {
    filename: 'test.jpeg',
    encoding: '7bit',
    mimeType: 'image/jpeg',
    uploadedPath: 'uploads/file9-test.jpeg-1655893178067.jpeg'
  },
  uploadedFile: {
    uploadedName: 'file9-test.jpeg-1655893178067',
    uploadedPath: 'uploads/file9-test.jpeg-1655893178067.jpeg',
    uploadDuration: 1,
    success: true,
    fileInfo: {
      _readableState: [Object],
      _events: {},
      _eventsCount: 0,
      truncated: false,
      _readcb: null
    },
    size: 89090
  }
}

File has been not been successfully uploaded:

{
  errors: [ 'FILE_TYPE_NOT_ALLOWED' ],
  originalFile: {
    filename: 'bomb.zip',
    encoding: '7bit',
    mimeType: 'application/zip'
  },
  uploadedFile: {
    uploadedName: 'bomb9-bomb.zip-1655893178067',
    uploadedPath: 'uploads/bomb9-bomb.zip-1655893178067.zip',
    uploadDuration: 0,
    success: false,
    fileInfo: {
      _readableState: [Object],
      _events: {},
      _eventsCount: 0,
      truncated: false,
      _readcb: null
    }
  }
}

Note: The file size is provided in Bytes

Errors

The parameter error of a file returns one of these following errors. In the table below, you can learn how to deal with errors

Error | Meaning --- | --- FILE_TYPE_NOT_ALLOWED | The filetype does not match the provided query UPLOADED_FILE_TO_BIG | The provided file exeedes the provided limit of bytes MAXIMUM_FILE_AMOUNT_REACHED | The maximum file size has been reached, no files after the limit will be uploaded FILE_TYPE_NOT_ALLOWED | The mime type is not allowed to be uploaded

Note: Other errors could occoure, in this case you probably did something wrong whith the config, open a new issues

Test your code with axios

To test your code, you can start uploading file with axios. For that, you need to have form-data, fs and axios installed, you can do that by running:

$ npm install fs form-data axios

Sample code:


const formData = require('form-data');
const fs = require('fs');

const axios = require('axios').default;

const init = async () => {
    const fd = new formData();

    fd.append('cat', fs.createReadStream('./miau.jpeg'));
    fd.append('dog', fs.createReadStream('./dog.jpeg'));

    const res = await axios.post('http://127.0.0.1:443/upload', fd, {
        maxBodyLength: Infinity,
        maxContentLength: Infinity,
            headers: {
                ...fd.getHeaders()
            }
    }).then(res => {
        console.log(res.data);
    }).catch(err => console.log(err));
}

init();

Made by Robert J. Kratz

License

MIT