Skip to content

Instantly share code, notes, and snippets.

@frankie567
Last active April 3, 2018 06:38
Show Gist options
  • Save frankie567/69c00679da836c51ae1319f019c85769 to your computer and use it in GitHub Desktop.
Save frankie567/69c00679da836c51ae1319f019c85769 to your computer and use it in GitHub Desktop.
NodeJS : upload a file with a speed limit
import { createReadStream } from 'fs'
import { basename } from 'path'
import * as request from 'request' // npm i request
import * as Throttle from 'throttle' // npm install throttle
const fileToUploadPath = '/foo.txt'
const fileSize = 1024 // Computed with 'fs.stat' for example
request.post(
'/upload',
{
formData: {
foo: 'bar',
file: {
// Create a ReadStream from the file, pipe it to a Throttle transform stream with a limit in bytes per second
value: createReadStream(fileToUploadPath).pipe(new Throttle(512 * 1024)),
// Because it's not a pure ReadStream, we have to provide manually the metadata
// See: https://github.com/request/request#multipartform-data-multipart-form-uploads
options: {
filename: basename(fileToUploadPath),
knownLength: fileSize,
},
},
}
},
() => console.log('Upload finished!')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment