Tuesday 9 May 2017

download file from url to server using node.js

I need a requirement to download file from any url to the server that running the app. I used the following code in Node.js. And its working in the case of localhost. But not in the case of server.

var express = require('express');
var app     = express();
var http    = require('http');
var https   = require('https');
var request = require('request');
var fs      = require('fs');
var path    = require('path');

app.get('/', function( request, response ){
    response.send('connection established...!');
});

app.get('/download', function(request, response){
    var file     = "http://fodof.net/gemlia/public/uploads/shanks/ctm/shank1-shankparts_1.ctm";

    var filename = path.basename( file );
    var ssl      = file.split(':')[0];
    var dest     = __dirname +'downloads/'+ filename;
    var stream   = fs.createWriteStream( dest );

    if ( ssl == 'https') {
        https.get( file, function( resp ) {
            resp.pipe( stream );
            response.send('file saved successfully.*');
        }).on('error', function(e) {
            response.send("error connecting" + e.message);
        });
    } else {
        http.get( file, function( resp ) {
            resp.pipe( stream );
            response.send('file saved successfully.*');
        }).on('error', function(e) {
            response.send("error connecting" + e.message);
        });
    }
});
app.listen(process.env.PORT || 3000);



via Rishi R

No comments:

Post a Comment