Sunday, 4 June 2017

How to serve image from Node Server without Express?

I am working on Node v6.10.2. I am trying to serve static elements with a simple NodeJS program. When I run the below mentioned code and go to http://localhost:3000/, I get this.

enter image description here

The image does not get retrieved here. But when I go to http://localhost:3000/img/logo.jpg, I get the image. How do I resolve this issue?

This is the server code

var http = require('http');
var fs = require('fs');

function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode = 200;

    // __dirname will resolve to the directory the executing script resides in.
    // So if your script resides in /home/sites/app.js, __dirname will resolve
    // to /home/sites.

    console.log(__dirname + path);

    fs.readFile(__dirname + path, function(err, data) {
        if(err) {
            res.writeHead(500, { 'Content-Type' : 'text/plain' });
            res.end('500 - Internal Error');
        } 
        else {
            res.writeHead( responseCode, { 'Content-Type' : contentType });
            res.end(data);
        }
    });
}

http.createServer( function (req, res) {
    var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    switch(path) {
        case '':
            serveStaticFile(res, '/public/home.html', 'text/html');
            break;
        case '/about':
            serveStaticFile(res, '/public/about.html', 'text/html');
            break;
        case '/img/logo.jpg':
            serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');
            break;
        default:
            serveStaticFile(res, '/public/404.html', 'text/html', 404);
            break;
    }
}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate...');

This is the html file - home.html

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    Welcome Home!!!
    <img href="localhost:3000/img/logo.jpg" alt="logo">
</body>
</html>



via Shashank

No comments:

Post a Comment