NodeJs Send File Http

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

var args = process.argv.slice(2);
var	filepath= args[0],
  port=args[1];
var filename = path.basename(filepath);
if(!filepath){
console.log('filepath is required');
process.exit();
}
if(!port){
port=2000;
}
console.log('File is sending at http://localhost:'+port);

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, filepath);
    var stat = fileSystem.statSync(filePath);
    response.writeHead(200, {
        'Content-Disposition': 'attachment; filename="'+filename+'"',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(port);

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *