node.js http server respond with an image by request
Objective: Create node js http server accepting requests with a query parameter image containing the an image name, respond with the image specified in the query.
Solution: Include http, url and fs node modules. Use http to create http server, url to parse the incoming request to get the image name, fs to read the image file and respond with the content from fs read.
[code language=”javascript”]
//include http, fs and url module
var http = require(‘http’),
fs = require(‘fs’),
url = require(‘url’);
//create http server listening on port 3333
http.createServer(function (req, res) {
//use the url to parse the requested url and get the image name
var query = url.parse(req.url,true).query;
pic = query.image;
//read the image using fs and send the image content back in the response
fs.readFile(‘/path/to/an/image/directory/’ + pic, function (err, content) {
if (err) {
res.writeHead(400, {‘Content-type’:’text/html’})
console.log(err);
res.end("No such image");
} else {
//specify the content type in the response will be an image
res.writeHead(200,{‘Content-type’:’image/jpg’});
res.end(content);
}
});
}).listen(3333);
console.log("Server running at http://localhost:3333/");
[/code]
Requesting an image with name tree.jpg
http://localhost:3333/?image=tree.jpg
Search within Codexpedia
Search the entire web