Last active
April 3, 2018 06:38
-
-
Save frankie567/69c00679da836c51ae1319f019c85769 to your computer and use it in GitHub Desktop.
NodeJS : upload a file with a speed limit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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