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; |
@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...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/**
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
fs = require('fs');
var vcapServices = require('vcap_services');
var SpeechToTextv1 = require('watson-developer-cloud/speech-to-text/v1');
var fs = require('fs');
var speech_to_text = new SpeechToTextv1 ({
username: "2b748554-abac-40b0-b2e1-e81eefe1e034",
password: "htUso1m85Ebh"
});
var params = {
model: 'en-US_BroadbandModel',
content_type: 'audio/flac',
'interim_results': true,
'max_alternatives': 3,
'word_confidence': false,
timestamps: false,
keywords: ['colorado', 'tornado', 'tornadoes'],
'keywords_threshold': 0.5
};
var recognizeStream = speech_to_text.createRecognizeStream(params);
var app = express();
var db;
var cloudant;
var fileToUpload;
var dbCredentials = {
dbName: 'my_sample_db'
};
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty')
var multipartMiddleware = multipart();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));
// development only
if ('development' ===app.get('env')) {
app.use(errorHandler());
}
function getDBCredentialsUrl(jsonData) {
var vcapServices = JSON.parse(jsonData);
// Pattern match to find the first instance of a Cloudant service in
// VCAP_SERVICES. If you know your service key, you can access the
// service credentials directly by using the vcapServices object.
for (var vcapService in vcapServices) {
if (vcapService.match(/cloudant/i)) {
return vcapServices[vcapService][0].credentials.url;
}
}
}
function initDBConnection() {
//When running on Bluemix, this variable will be set to a json object
//containing all the service credentials of all the bound services
if (process.env.VCAP_SERVICES) {
dbCredentials.url = getDBCredentialsUrl(process.env.VCAP_SERVICES);
} else { //When running locally, the VCAP_SERVICES will not be set
}
initDBConnection();
app.get('/', routes.index);
function createResponseData(id, name, value, attachments) {
}
function sanitizeInput(str) {
return String(str).replace(/&(?!amp;|lt;|gt;)/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
var saveDocument = function(id, name, value, response) {
}
app.get('/api/favorites/attach', function(request, response) {
var doc = request.query.id;
var key = request.query.key;
});
app.post('/api/favorites/attach', multipartMiddleware, function(request, response) {
// Pipe out the transcription to a file.
recognizeStream.pipe(fs.createWriteStream('/downloads/transcription.txt'));
// Get strings instead of buffers from 'data' events.
recognizeStream.setEncoding('utf8');
// Listen for events.
recognizeStream.on('results', function(event) { onEvent('Results:', event); });
recognizeStream.on('data', function(event) { onEvent('Data:', event); });
recognizeStream.on('error', function(event) { onEvent('Error:', event); });
recognizeStream.on('close', function(event) { onEvent('Close:', event); });
recognizeStream.on('speaker_labels', function(event) { onEvent('Speaker_Labels:', event); });
// Displays events on the console.
function onEvent(name, event) {
console.log(name, JSON.stringify(event, null, 2));
}
db.get(document.id, function(err, doc) {
console.log('Attachements from server --> ' + JSON.stringify(doc._attachments));
});
app.post('/api/favorites', function(request, response) {
});
app.delete('/api/favorites', function(request, response) {
});
app.put('/api/favorites', function(request, response) {
});
app.get('/api/favorites', function(request, response) {
});
http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
console.log('Express server listening on port ' + app.get('port'));
});
Can you write download function according to my code..