NODE JS
Node.js is a very popular server-side platform built on Google Chrome's JavaScript Engine. This uses an event driven, non-blocking I/O model that make it lightweight and efficient.
How to create a simple application using NodeJS?
1) As the first step we need to install NodeJs to the computer by visiting the website, https://nodejs.org
2) After that we have to open a IDE and create a new Node Project.
3) First create a JavaScript file name Server.js inside the Node Project and add this code
var http = require("http");
function onRequest(request,response)
{
console.log("A user made a request" + request.url);
response.writeHead(200,{"Context-Type":"text/plain"});
response.write("Here is some data");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("server is running");
4) when you run this application and visit http://localhost:8888/ from Google Chrome You can see the Hello world text appear on the screen.
How to run a html code in the web server using nodeJS
1) In the Server.js file type the following code part
var http = require("http");
var fs = require('fs');
//404 Response
function send404Respose(response)
{
response.writeHead(404,{"Context-Type":"text/plain"});
response.write("Error 404: Page not found");
response.end();
}
//handle a User request
function onRequest(request,response)
{
if(request.method == 'GET' && request.url == '/')
{
response.writeHead(200,{"Context-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
}
else
{
send404Respose(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("server is running");
2) create index.html file and create a small html page for ex:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Sri Lanka Institute of Information Technology</h1>>
</body>
</html>
3) Now when you run the Server.Js file we can clearly see that the index.html file is hosted on the local server.


No comments:
Post a Comment