Skip to content

Instantly share code, notes, and snippets.

@moeiscool
Forked from PaulMougel/client.js
Created October 18, 2018 23:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moeiscool/2d41335b7a87f8f273e2ea219519c09c to your computer and use it in GitHub Desktop.
Save moeiscool/2d41335b7a87f8f273e2ea219519c09c to your computer and use it in GitHub Desktop.
File upload in Node.js to an Express server, using streams
// node: v0.10.21
// request: 2.27.0
var request = require('request');
var fs = require('fs');
var r = request.post("http://server.com:3000/");
// See http://nodejs.org/api/stream.html#stream_new_stream_readable_options
// for more information about the highWaterMark
// Basically, this will make the stream emit smaller chunks of data (ie. more precise upload state)
var upload = fs.createReadStream('f.jpg', { highWaterMark: 500 });
upload.pipe(r);
var upload_progress = 0;
upload.on("data", function (chunk) {
upload_progress += chunk.length
console.log(new Date(), upload_progress);
})
upload.on("end", function (res) {
console.log('Finished');
})
// node: v0.10.7
// express: 3.4.4
var fs = require('fs');
var express = require('express');
var app = express();
app.post('/', function (req, res, next) {
req.pipe(fs.createWriteStream('./uploadFile'));
req.on('end', next);
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment