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

@happylinks/upchunk

v1.0.9

Published

Dead simple chunked file uploads using Fetch

Downloads

4

Readme

UpChunk

UpChunk

UpChunk uploads chunks of files! It's a JavaScript module for handling large file uploads via chunking and making a put request for each chunk with the correct range request headers. Uploads can be paused and resumed, they're fault tolerant, and it should work just about anywhere.

UpChunk is designed to be used with Mux direct uploads, but should work with any server that supports resumable uploads in the same manner. This library will:

  • Split a file into chunks (in multiples of 256KB).
  • Make a PUT request for each chunk, specifying the correct Content-Length and Content-Range headers for each one.
  • Retry a chunk upload on failures.
  • Allow for pausing and resuming an upload.

Installation

NPM

npm install --save @mux/upchunk

Yarn

yarn add @mux/upchunk

Script Tags

<script src="https://unpkg.com/@mux/upchunk@1"></script>

Basic Usage

Getting an upload URL from Mux.

You'll need to have a route in your application that returns an upload URL from Mux. If you're using the Mux Node SDK, you might do something that looks like this.

const { Video } = new Mux();

module.exports = async (req, res) => {
  // This ultimately just makes a POST request to https://api.mux.com/video/v1/uploads with the supplied options.
  const upload = await Video.Uploads.create({
    cors_origin: 'https://your-app.com',
    new_asset_settings: {
      playback_policy: 'public',
    },
  });

  // Save the Upload ID in your own DB somewhere, then
  // return the upload URL to the end-user.
  res.end(upload.url);
};

Then, in the browser

import * as UpChunk from '@mux/upchunk';

// Pretend you have an HTML page with an input like: <input id="picker" type="file" />
const picker = document.getElementById('picker');

picker.onchange = () => {
  const getUploadUrl = () =>
    fetch('/the-endpoint-above').then(res =>
      res.ok ? res.text() : throw new Error('Error getting an upload URL :(')
    );

  const upload = UpChunk.createUpload({
    endpoint: getUploadUrl,
    file: picker.files[0],
    chunkSize: 5120, // Uploads the file in ~5mb chunks
  });

  // subscribe to events
  upload.on('error', err => {
    console.error('💥 🙀', err.detail);
  });

  upload.on('progress', progress => {
    console.log(`So far we've uploaded ${progress.detail}% of this file.`);
  });

  upload.on('success', () => {
    console.log("Wrap it up, we're done here. 👋");
  });
};

API

createUpload(options)

Returns an instance of UpChunk and begins uploading the specified File.

options object parameters

  • endpoint type: string | function (required)

    URL to upload the file to. This can be either a string of the authenticated URL to upload to, or a function that returns a promise that resolves that URL string. The function will be passed the file as a parameter.

  • file type: File (required)

    The file you'd like to upload. For example, you might just want to use the file from an input with a type of "file".

  • headers type: Object

    An object with any headers you'd like included with the PUT request for each chunk.

  • chunkSize type: integer, default:5120

    The size in kb of the chunks to split the file into, with the exception of the final chunk which may be smaller. This parameter should be in multiples of 256.

  • retries type: integer, default: 5

    The number of times to retry any given chunk.

  • delayBeforeRetry type: integer, default: 1

    The time in seconds to wait before attempting to upload a chunk again.

UpChunk Instance Methods

  • pause()

    Pauses an upload after the current in-flight chunk is finished uploading.

  • resume()

    Resumes an upload that was previously paused.

UpChunk Instance Events

Events are fired with a CustomEvent object. The detail key is null if an interface isn't specified.

  • attempt { detail: { chunkNumber: Integer, chunkSize: Integer } }

    Fired immediately before a chunk upload is attempted. chunkNumber is the number of the current chunk being attempted, and chunkSize is the size (in bytes) of that chunk.

  • attemptFailure { detail: { message: String, chunkNumber: Integer, attemptsLeft: Integer } }

    Fired when an attempt to upload a chunk fails.

  • error { detail: { message: String, chunkNumber: Integer, attempts: Integer } }

    Fired when a chunk has reached the max number of retries or the response code is fatal and implies that retries should not be attempted.

  • offline

    Fired when the client has gone offline.

  • online

    Fired when the client has gone online.

  • progress { detail: [0..100] }

    Fired after successful chunk uploads and returns the current percentage of the file that's been uploaded (in terms of chunks).

  • success

    Fired when the upload is finished successfully.

Credit

The original idea and base for this came from the awesome huge uploader project, which is what you need if you're looking to do multipart form data uploads. 👏