Let me write the program and will explain line by line.
http = require(‘http’)
res.end(“<h2>This is the end!</h2>”);
console.log(“Server running at http://127.0.0.1:3000/”)
Let’s create a new file called
Now Node comes with a handfull of libraries to make the development of event-based servers easy.
To use one of the available libraries, We simply include its module using the require function.
http_object = require(‘http’)
The require function will return an object representing the module that you pass into it and you can capture that object in a variable.
For running app, we need to create HTTP server. Node provides the http library. With reference to http_object create server.
createServer that takes a callback function and returns a new server object.
The callback function is what Node calls a listener function and it is called by the server whenever a new request comes in.
Whenever an HTTP request is made, the listener function will be called and objects representing the HTTP request and response will be passed into the function.
Then first need to write the appropriate HTTP headers.
writeHead function takes a couple of arguments. The first is an integer value representing the status code of the request which for us will be 200, in other words,
Then we’ll call the
write function and pass in the data that you wish to send.
Now that we’ve created our server, we need to set it up to listen for new requests.
The listen function on our server object and pass in a port number for it to listen on(3000). The listen function also takes an optional second parameter which is the hostname URL(“127.0.0.1”),
Finally, let’s print out a message to let us know that our server is running
Listening on http://127.0.0.1:3000“).
There we go, now let’s run our app by calling node and passing to it the name of the file we want it to execute.
node hello_world.js and open browser “
That’s it. Enjoy………………..