Saturday, January 21, 2017

Nodejs Intro

Nodejs introduction




Nodejs is having lots of inbuilt modules/packages and also custom packages (npm manages packages). 

Fine, Now how to use those packages? 

Simple - just use require('<package name>') (commonjs approch).

Example - var http = require('http');

(Here we can see http module is imported. You can import multiple modules as required.)

Note: Any javascript code is valid under nodejs, as it uses V8.

Start the server-side coding using Javascript-

    var http = require('http');
    
    function onRequest(request, response){
        console.log('request '+ request.url);
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end()
       
    }
    http.createServer(onRequest).listen(9000);
    console.log('Server Running');

Now save it, say server.js.

To run this application run following in console - 

> node server.js

Server Running // this line will be printed in console.

Cool, it's running. 

Now if you open localhost:9000, you will see "Server running" text in the page.

Congratulation it's your first nodejs application. 

Post a Comment