NodeJs Send File Http

Posted by dogukanhan on October 13, 2018 · 1 min read
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);