I am trying to figure out a way using just Node.js to display image on the client's browser. With my code I can only make .png files display , .svg and .gif files get downloaded instead of displayed. Why is this?
I am using this:
var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer(function(req,res) {
if(path.extname(req.url) == ".gif") {
fs.readFile(path.basename(req.url), function(err, data) {
res.writeHead(200, {'content-type':'image/gif'});
res.end(data);
});
}
});
server.listen(80);
I tested .gif .png. .svg , also changing the content type to the correct file extension name. PNG displays and the rest just get downloaded.
Not looking for a framework solution like Express I want to understand how node.js works and why this is happening.
There was nothing wrong with my code. Only certain gifs and svgs did not show. Probably corrupt files. I tried many other gifs and svgs and it worked properly