I am trying to write some code in node.js that uses the extension name of a url to find images. For example if the extension name of the url is .jpg , it will find and respond with the .jpg file. If the url extension name is .png or .svg it will serve the appropriate file with the correct file type.
This is what I have:
var http = require('http');
var path = require('path');
var fs = require('fs');
var server = http.createServer(function(req, res) {
if(path.extname(req.url) == ".png" || path.extname(req.url) == ".gif" || path.extname(req.url) == ".svg") {
fs.readFile(path.basename(req.url), function(err, data) {
var extname = path.extname(req.url);
switch(extname) {
case ".png":
var ext = "image/png";
case ".svg":
var ext = "image/svg+xml";
case ".gif":
var ext = "image/gif";
}
res.writeHead(200, {'content-type':ext});
res.end(data);
console.log(ext);
});
}
});
server.listen(80);
This is driving me nuts because when I observe the headers, its not using the correct content-type. I used a switch statement to put the correct content type into a variable based on the extension name. So if the extension name is .png , it would put "image/png" into a variable called ext. I put the variable ext in the writeHead section right after 'content-type': ...
I am console logging the variable "ext" and I am getting "image/gif" no matter what. Even if the extname is .svg or .png.
At this moment if I look for a file on my server domain.com/picture.svg and check the headers, it will show : content-type:image/gif ..My switch statement clearly says if the path.extname(req.url) is ".svg", then "image/svg+xml" should be put in the variable ext.
I tried weird things like put quotes around the variable "ext" and it actually displays the .svg file that I requested. Even though the headers look like this: content-type:ext.
I am very confused and I need some help.
What is wrong with my code? How do I display .jpg .png .svg .gif using only a block of a code in node.js?
NO EXPRESS OR FRAMEWORKS! I am looking for a pure node.js solution.
In your code it seems you're missing "break" on each case and that's why it evaluates all the way to the last case? Read the reasons behind this at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Example: What happens if I forgot a break?
If you forget a break then script will run from the case where criteria is met, and will run the case after that regardless if criteria was met.
Your code should look (more) like:
var extname = path.extname(req.url);
var allowed = [".png", ".gif", ".svg"];
var ext = "";
if (!!~allowed.indexOf(extname)) {
fs.readFile(path.basename(req.url), function(err, data) {
switch(extname) {
case ".png":
ext = "image/png";
break;
case ".svg":
ext = "image/svg+xml";
break;
case ".gif":
ext = "image/gif";
break;
}
res.writeHead(200, {'content-type':ext});
res.end(data);
});
}