Node.js comes with built-in http module and it is simple and straight-forward to create a HTTP Server. The following example shows how to create an HTTP server with Nodejs.
// Import http module var http = require("http"); // Port at which Server will Listen const PORT = 8080; var server = http.createServer(function (request, response) { // Send the HTTP header with Status: 200 : OK and Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World'); }); server.listen(PORT, function() { // Message to show at console console.log('Server running at http://localhost:%s/', PORT); });
Put this code in a file main.js and execute it to start the server:
C:\MyApp>node main.js Server running at http://localhost:8080/
If you open http://localhost:8080/ in browser, it shows the text Hello World.
In this program require("http") will load the http module. The require function usually reads a file, executes it and returns its exports object. In this case the return object is assigned to variable called http. The constant PORT hold the value of port number, if you want to change it anytime just modify the value.
Now the http.createServer() method is invoked to create a server object. This method can take a request handler function as an argument. In our case, the request handler is
function (request, response) { // Send the HTTP header with Status: 200 : OK and Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World'); }
The request handler is invoked everytime the server receives a request. The response.writeHead()
method creates header. The body of the response can be written with response.write()
. The response is ended with response.end()
method.
Instead of writing
response.write('Hello World'); response.end();
We can just write
response.end('Hello World');
because response.end()
can have optional argument which holds the last part of data.
Now our server is created, we ask it to listen at the desired port number. The server.listen()
method also takes arguments port number and call back function to be executed. Our call back function is
function() { console.log('Server running at http://localhost:%s/', PORT); }
When server start to listen successfully, the call back is invoked and you can see the output on the terminal window.
Nothing yet..be the first to share wisdom.