Last active
January 7, 2021 23:07
-
-
Save alanhoff/fe17f8cbc1888110ba33 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var download = require('./lib/download'); | |
download('http://meuarquivolocodedoido.com.br/arquivo.txt', './downloads') | |
.then(function(id){ | |
console.log('Arquivo gravado com id %s', id); | |
}) | |
.catch(function(err){ | |
console.log('Deu pau..'); | |
console.log(err.stack); | |
}); | |
// Ou como callback | |
download('http://meuarquivolocodedoido.com.br/arquivo.txt', './downloads', function(err, id){ | |
if(err) | |
throw err; | |
console.log('Arquivo gravado com id %s', id); | |
}); |
This file contains hidden or 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
var request = require('request'); | |
var fs = require('fs'); // fs para escrever diretamente para o disco, much win | |
var Puid = require('puid'); | |
var puid = new Puid(); // Isso aqui gera ID únicos, assim nunca vai sobreescrever | |
var path = require('path'); | |
var Promise = require('bluebird'); | |
var download = function(arquivo, pasta, callback){ | |
var p = new Promise(function(resolve, reject){ | |
var id = puid.generate(); | |
var dest = path.join(pasta, id); | |
var writeStream = fs.createWriteStream(dest); | |
// Avisando a promise que acabamos por aqui | |
writeStream.on('finish', function(){ | |
resolve(id); | |
}); | |
// Capturando erros da write stream | |
writeStream.on('error', function(err){ | |
fs.unlink(dest, reject.bind(null, err)); | |
}); | |
var readStream = request.get(arquivo); | |
// Capturando erros da request stream | |
readStream.on('error', function(err){ | |
fs.unlink(dest, reject.bind(null, err)); | |
}); | |
// Iniciando a transferência de dados | |
readStream.pipe(writeStream); | |
}); | |
// Manter compatibilidade com callbacks | |
if(!callback) | |
return p; | |
p.then(function(id){ | |
callback(null, id); | |
}).catch(function(err){ | |
callback(err); | |
}); | |
}; | |
module.exports = download; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ManojKuppaiahSudhakara, you might want to edit your post and delete your Watson credentials from the code you posted, just in case they're for real...