Created
December 11, 2014 02:29
-
-
Save nitely/61d7af573d934696bcf2 to your computer and use it in GitHub Desktop.
node-downloaderJS using coroutines and generators
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
/* This is just a cool example on how to write coros in javascript Ecma6. | |
* Licence: MIT | |
* Author: esteban castro borsani | |
*/ | |
var http = require('http'); | |
var fs = require('fs'); | |
var path = require('path'); | |
var Q = require("q"); | |
var co = require("co"); | |
function request(opts) { | |
var deferred = Q.defer(); | |
http.request(opts, deferred.resolve) | |
.on('error', deferred.reject) | |
.end(); | |
return deferred.promise; | |
} | |
function pipe(readable, writtable, progressUpdate) { | |
var deferred = Q.defer(); | |
function ondata(){ | |
progressUpdate(writtable.bytesWritten); | |
} | |
function onfinish(){ | |
progressUpdate(writtable.bytesWritten); | |
deferred.resolve(); | |
} | |
readable.on('data', ondata) | |
.on('error', deferred.reject); | |
writtable.on('error', deferred.reject) | |
.on('finish', onfinish); | |
readable.pipe(writtable); | |
return deferred.promise; | |
} | |
function update(bytesWritten) { | |
// show progress somewhere | |
} | |
function* downloadCoro() { | |
var execPath = path.dirname(process.execPath); | |
var destPath = execPath + "/downloads/out"; | |
var file = fs.createWriteStream(destPath, {flags: 'w', encoding: null}); | |
try { | |
var res = yield request({host: "releases.ubuntu.com", path: "/14.04.1/ubuntu-14.04.1-desktop-amd64.iso"}); | |
yield pipe(res, file, update); | |
} catch (err) { | |
console.error(err.stack); | |
} | |
} | |
var download = coWrapper(downloadCoro); | |
function coWrapper(coro){ | |
return function (){ | |
co(coro).catch(onerror); | |
} | |
} | |
function onerror (err) { | |
console.error(err.stack); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment