node.js http server displaying images from a directory

Objective: Create a node.js http server displaying a list image names with hyper links for all jpg images in an image directory on the server. The image will be displayed when the hyper link is clicked.
Solution: Include http, fs, url and path node modules. http for creating the http server, fs for reading image files, url for getting http request query parameter and path getting the file ext. First create http server. If the request doesn’t have file name in the request query, then get the list of jpg images in the image directory and construct htm ul lists to be sent back to the browser. If the request doesn’t contain file name in the request query, read the image and send it back to the browser to be displayed.

//include http, fs and url module
var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    url = require('url');
    imageDir = '/Users/peng/ifs/ipic/x/';

//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;

    if (typeof pic === 'undefined') {
        getImages(imageDir, function (err, files) {
            var imageLists = '<ul>';
            for (var i=0; i<files.length; i++) {
                imageLists += '<li><a href="/?image=' + files[i] + '">' + files[i] + '</li>';
            }
            imageLists += '</ul>';
            res.writeHead(200, {'Content-type':'text/html'});
            res.end(imageLists);
        });
    } else {
        //read the image using fs and send the image content back in the response
        fs.readFile(imageDir + 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/");

//get the list of jpg files in the image dir
function getImages(imageDir, callback) {
    var fileType = '.jpg',
        files = [], i;
    fs.readdir(imageDir, function (err, list) {
        for(i=0; i<list.length; i++) {
            if(path.extname(list[i]) === fileType) {
                files.push(list[i]); //store the file name into the array files
            }
        }
        callback(err, files);
    });
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search