Wednesday, December 7, 2016

First HTTP Server in Node.js

1. Download node server from here or here and extract to a local folder
2. Download NPM (Node Package Manager) from here or here and extract to a local folder
3. Configure environment PATH Variable. Open command prompt and do the following:
C:\Users\pritom>set PATH=%PATH%;C:\Users\..\NODE_FOLDER;C:\Users\..\NPM_FOLDER

C:\Users\pritom>echo %PATH%
...;C:\Users\pritom\Desktop\codes\node_1\node-v7.2.1-win-x64;C:\Users\pritom\Desktop\codes\node_1\npm-4.0.5

C:\Users\pritom>node --version
v7.2.1

4. Create a file named "server.js" in a local folder with following contents:



//Lets import the HTTP module
var http = require('http');

//Lets define a port we want to listen to
const PORT = 5555;

//We need a function which handles requests and send response
function handleRequest(request, response) {
    response.end('Node js server browse at: [[http://localhost:' + PORT + request.url + ']]');
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function () {
    //Callback triggered when server is successfully listening.
    console.log("Server listening on: http://localhost:%s", PORT);
});



5. Now navigate to the folder using command prompt and type "node server.js" will output:
Server listening on: http://localhost:5555

6. Hit "http://localhost:5555" in your browser and see the result.....

No comments:

Post a Comment