Last active
August 29, 2015 14:16
-
-
Save didasy/50f5e85692f512e13983 to your computer and use it in GitHub Desktop.
A piece of code to upload a file to a remote server using HTTP POST with request.js
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
/* | |
* Node.js file upload using request.js, the example | |
* Does not work in Node.js v0.12.x yet @2015-03-05 using request.js@2.35.1 | |
* Usage : node FileUpload.js /my/path/to/file.txt http://mysite/upload 10 3000 | |
*/ | |
var fs = require("fs"), | |
request = require("request"), | |
filepath = process.argv[2], | |
targetUrl = process.argv[3], | |
gretries = parseInt(process.argv[4], 10) || 3, | |
interval = parseFloat(process.argv[5]) || 1000; | |
if (isNaN(gretries)) { | |
gretries = Infinity; | |
} | |
/* | |
* Request will automatically put correct content-type | |
* This function will also retrying for gretries times with interval interval if the upload process got failed | |
*/ | |
function fileUpload(retries, interval) { | |
fs.createReadStream(filepath) | |
.pipe( | |
request | |
.post(targetUrl, function postHandler(err, res, body) { | |
if (err) { | |
process.stderr.write("Error : ", err); | |
process.stderr.write("Exiting..."); | |
process.exit(1); | |
return; | |
} | |
if (res.statusCode !== 200) { | |
process.stdout.write("There is a server error, retrying..."); | |
if (retries <= 0) { | |
process.stderr.write("Failed in " + gretries + " retries, there is a persistent connection or server error: exitting..."); | |
process.exit(1); | |
return; | |
} | |
setTimeout(fileUpload, interval, retries, interval); | |
return; | |
} | |
process.stdout.write("Uploading file " + filepath + " to " + targetUrl + " success"); | |
process.exit(0); | |
}); | |
); | |
} | |
fileUpload(gretries, interval); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment