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');
    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. 

Friday, January 20, 2017



Setup Mongo

Download & Install Mongo from- MongoDB site

Now you need a folder to store the data. So, Create one and Setup mongo.

Run MongoDB command in console-

mongod --directoryperdb --dbpath <folder path> --logpath <file path> --logappend --rest 

Mongo commands

Great, you are ready to do DB functionalities. For this, you have to run following command in the console. 


That's it. It will open a shell for executing mongo commands.

Show list of DBs-
>show DBS

Create/Use the DB-
>use local

See selected DB-

Create user for db-
>db.createUser({user:"test",pwd:"1234",roles: ["readWrite","dbAdmin"]});

Create a collection in DB-

Show all collections in DB-
>show collections

Insert document in a collection-
>db.employee.insert({first_name:"sudhir", last_name:"ghosh"});

Fetch the documents-

Insert multiple documents-
>db.employee.insert([{first_name:"sakti", last_name:"ghosh"},{first_name:"subha", last_name:"ghosh", gender:"M"}]);

Get Collection-

Update commands -
>db.employee.update({first_name:"sakti"},{first_name:"sakti", last_name:"ghosh",gender:"M"});

>db.employee.update({first_name:"sudhir",{$set:{age: 40}});



>db.employee.update({first_name:"rnga"},{first_name:"ranga", last_name:"ghosh"},{upsert:true});


Remove commands -

>db.employee.remove({first_name:"rnga"}, {justOne:true});

Find Commands -


>db.employee.find({age:{$lt:40}}); //$gt/$gte/$lte

>db.employee.find({"":"kol"});//json path

>db.employee.find().sort({last_name:1});//asc/desc (-1)




print('name:'+ oc.first_name)});

Further study -