Friday, 19 October 2018

Node.js: http: Serving html page

In my previous post, I explained how to serve the contents of a document. In this post, I am going to explaine how to serve a html page.

Requirements
a.   When user hits the url ‘http://localhost:9000/’, server should send the the contents of the index.html page.
b.   index.jsp should refer a style sheet file and an image
c.   Resources like styles.css and image.jpg should located at resources folder.

Files are presented in below directory structure.




As you see above image, index.html, HelloWorld.js are in the same directory. Where as styles.css, image.jpg are located at resources folder.

index.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="resources/styles.css">
</head>

<body>

    <h1>Welcome to node.js programming</h1>

    <img src="resources/image.jpg" alt="Node.js Logo" , width="460" height="345">

</body>

</html>

styles.css

h1{ 
 color: green 
}


image.jpg

HelloWorld.js

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

var filePath = 'index.html';

var server = http.createServer((request, response) => {
    console.log(`Requested Resource: ${request.url}`);
    if (request.url === '/') {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });

        var readableStream = fs.createReadStream(filePath, {
            encoding: 'utf-8'
        });

        readableStream.pipe(response);
    } else {
        console.log(`${request.url} Resource not available`);
        response.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        response.end('Resource not available');
    }

});

server.listen(9000);

console.log('Server started and listening on port 9000');

let’s run HelloWorld.js application.

Hit the url ‘http://localhost:9000/’ in the browser, you can see below screen.

you can see below messages in console.

Server started and listening on port 9000
Requested Resource: /
Requested Resource: /resources/styles.css
/resources/styles.css Resource not available
Requested Resource: /resources/images.jpg
/resources/images.jpg Resource not available

As you see the image and console logs, the image, style sheets are not rendered. It is because, our application ‘HelloWorld.js’ is not yet implemented to deliver styles.css and image.jpg.

How to send css files?
a.   We need to set the content type to 'text/css'
b.   While creating readable stream, set the encoding to 'utf-8'.

response.writeHead(200, {
    'Content-Type': 'text/css'
});

var readableStream = fs.createReadStream(cssFilePath, {
    encoding: 'utf-8'
});

readableStream.pipe(response);

How to send image file?
a.   Set the content type to 'image/jpeg'
c.   Since this is image file, we should send the response in binary format. While creating readable stream, do not set any encoding.

response.writeHead(200, {
    'Content-Type': 'image/jpeg'
});

var readableStream = fs.createReadStream(jpgFilePath);

readableStream.pipe(response);

Find the below working application.


HelloWorld.js

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

var filePath = 'index.html';

var server = http.createServer((request, response) => {
    console.log(`Requested Resource: ${request.url}`);
    if (request.url === '/') {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });

        var readableStream = fs.createReadStream(filePath, {
            encoding: 'utf-8'
        });

        readableStream.pipe(response);
    } else if (request.url === '/resources/styles.css') {
        var cssFilePath = path.join(__dirname, request.url);

        response.writeHead(200, {
            'Content-Type': 'text/css'
        });

        var readableStream = fs.createReadStream(cssFilePath, {
            encoding: 'utf-8'
        });

        readableStream.pipe(response);
    } else if (request.url === '/resources/image.jpg') {
        var jpgFilePath = path.join(__dirname, request.url);

        response.writeHead(200, {
            'Content-Type': 'image/jpeg'
        });

        var readableStream = fs.createReadStream(jpgFilePath);

        readableStream.pipe(response);
    } else {
        console.log(`${request.url} Resource not available`);
        response.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        response.end('Resource not available');
    }

});

server.listen(9000);

console.log('Server started and listening on port 9000');

Open the url ‘http://localhost:9000/’ in browser, you can see below screen.

You can see below messages in console.

Requested Resource: /
Requested Resource: /resources/styles.css
Requested Resource: /resources/image.jpg





Previous                                                 Next                                                 Home

No comments:

Post a Comment