Websocket and Html NodeJs

Following the earlier chapters in this Node.js tutorial, lets set up a web server that can serve HTML files.

Now lets set up a webserver. Create a Node.js file that opens the requested file and returns the content to the client. If anything goes wrong, throw a 404 error.

sudo nano webserver_basic.js

Then write the coding below:

var http = require(‘http’).createServer(handler); //require http server, and cr$
var fs = require(‘fs’) // require filesystem module

http.listen(8080); // listen to port 8080

function handler(req, res)
{
fs.readFile(__dirname + ‘/index_basic.html’,function(err,data)
{
res.writeHead(200,{‘Content-Type’: ‘text/html’});
res.write(data); //write data from index.html
return res.end();
});

}

And create a HTML file, index_basic.html:

sudo nano index_basic.html

Then write the following coding below:

index.html:<!DOCTYPE html>
<html>
<body>
<h1>Control LED light</h1>
<input id=”light” type=”checkbox”>LED
</body>
</html>

This file will not have any functionality yet. For now it is just a placeholder. Lets see if the webserver is working:

node webserver_basic.js

Open the website in a browser using http://[Your RaspberryPi_IP]:8080/:

The webserver should now be up and running, and we can move on to the WebSocket part.