I have a nodejs application where I have created project structure. package.json and index.js files, one json file also which I want that user can download it.
This is how my project structure
I have deployed nodejs application on heroku server. It is running perfectly, able to access index.js
How I can implement a functionality here so users can download swagger.json also. I tried to access this like https://heroku-address/swagger.json but it is showing only "Hello World"
index.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(process.env.PORT);
Let's start with defining server and app variables,
var express = require('express')
var app = module.exports = express();
Now,To show a tags on which if users click file will be downloaded,below is code to show links,
app.get('/', function(req, res){
res.send('<ul>'
+ '<li> <a href="/package.json">package.json</a>.</li>'
+ '<li> <a href="/swagger.json">swagger.json</a>.</li>'
+ '</ul>');
});
Now,When user clicks on one of the above link then code shown below will be executed,and file will be downloaded,
app.get('/:file(*)', function(req, res, next){
var file = req.params.file
, path = __dirname + '/' + file;
res.download(path);
});
finally code for listening on port,
app.listen(8080);
console.log('Express started on port %d', 8080);
So,your full server.js file will look like,
var express = require('express')
, app = module.exports = express();
app.get('/', function(req, res){
res.send('<ul>'
+ '<li>Download <a href="/package.json">package.json</a>.</li>'
+ '<li>Download <a href="/swagger.json">swagger.json</a>.</li>'
+ '</ul>');
});
app.get('/:file(*)', function(req, res, next){
var file = req.params.file
, path = __dirname + '/' + file;
res.download(path);
});
app.listen(8080);
console.log('Express started on port %d', 8080);