Showing posts with label NodeJS. Show all posts
Showing posts with label NodeJS. Show all posts

Monday 19 June 2017

underscore module with nodeJs tutorial

Underscore is a JavaScript library that provides a lot of useful helper functions to fast the node development. following are list of available array/object functions.

Question: What is underscore module?
Underscore is a JavaScript library that provides a lot of useful functional helpers without extending any built-in objects.



Question: How to install async module?
npm install underscore




Question: How to include request module in node project?
var _ = require("underscore");




Question: Give an example of each in underscore?
 
_.each(['Understand', 'underscore', 'Module'], function(value,pos){
    console.log(value+' stored at '+pos);    
});

Output
Understand stored at 0
underscore stored at 1
Module stored at 2




Question: What are other collections in underscore module?
each
map
reduce
reduceRight
find
filter
where
findWhere
reject
every
some
contains
invoke
pluck
max
min
sortBy
groupBy
indexBy
countBy
shuffle
sample
toArray
size
partition



Question: How to create a range array?
 
var lists=_.range(5);
console.log(_.first());




Question: How to get first nth element from array?
 
var lists=["One","two","three","four", "five"];
console.log(_.first(lists)); //One
console.log(_.first(lists,2)); //One two
console.log(_.first(lists,3)); //One two three




Question: How to check a variable is empty OR Not ?
var name=''
console.log(_.isEmpty(name));//true

name='Hello User'
console.log(_.isEmpty(name));//false




Question: What are array functions in underscore module?
first
initial
last
rest
compact
flatten
without
union
intersection
difference
uniq
zip
unzip
object
indexOf
lastIndexOf
sortedIndex
findIndex
findLastIndex
range



Question: How to get key value of an object data?
 
var lists={1:"One",2:"two",3:"three",4:"four", 5:"five"};
console.log(_.keys(lists)); //1,2,3,4,5




Question: What are the object functions in underscore module?
 
keys
allKeys
values
mapObject
pairs
invert
create
functions
findKey
extend
extendOwn
pick
omit
defaults
clone
tap
has
matcher
property
propertyOf
isEqual
isMatch
isEmpty
isElement
isArray
isObject
isArguments
isFunction
isString
isNumber
isFinite
isBoolean
isDate
isRegExp
isError
isNaN
isNull
isUndefined


Friday 16 June 2017

Async module with NodeJs tutorial

Example of parallel, concat and logs example in async? List all the methods available in async

Question: What is async module?
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.



Question: How to install async module?
npm install async




Question: How to include request module in node project?
var async = require('async');




Question: Concatenate the files from different directories?
 
async.concat(['data', 'data1'], fs.readdir, function(err, files) {
    if (err) {
        return console.log(err);
    }    
    /*files is now a list of filenames that exist in the 3 directories*/
    console.log(files);    
});




Question: What are other collection methods available in async ?
concat
concatSeries
detect
detectLimit
detectSeries
each
eachLimit
eachOf
eachOfLimit
eachOfSeries
eachSeries
every
everyLimit
everySeries
filter
filterLimit
filterSeries
groupBy
groupByLimit
groupBySeries
map
mapLimit
mapSeries
mapValues
mapValuesLimit
mapValuesSeries
reduce
reduceRight
reject
rejectLimit
rejectSeries
some
someLimit
someSeries
sortBy
transform




Question: Give an example of parallel in async?
async.parallel([
    function(callback) {
        setTimeout(function() {
            callback(null, 'one');
        }, 200);
    },
    function(callback) {
        setTimeout(function() {
            callback(null, 'two');
        }, 100);
    }
],
// optional callback
function(err, results) {
        console.log(results); //['one','two']
});




Question: What other control methods in async?
applyEach
applyEachSeries
auto
autoInject
cargo
compose
doDuring
doUntil
doWhilst
during
forever
parallel
parallelLimit
priorityQueue
queue
race
retry
retryable
seq
series
times
timesLimit
timesSeries
tryEach
until
waterfall
whilst




Question: Give an example of async.log?
var hello = function(name, callback) {
    setTimeout(function() {
        callback(null, 'hello ' + name);
    }, 1000);
};
async.log(hello, 'World 1'); //Hello World 1
async.log(hello, 'World 2'); //Hello World 2
async.log(hello, 'World 3'); //Hello World 3




Question: What other Utiles methods in async?
Utils
apply
asyncify
constant
dir
ensureAsync
log
memoize
nextTick
reflect
reflectAll
setImmediate
timeout
unmemoize



Thursday 15 June 2017

request module with nodeJs tutorial

How to post get/post request with parameter? How to send headers in ajax call.

Question: What is request module?
Request is designed to be the simplest way possible to make http/https calls.



Question: How to install request module?
npm install request




Question: How to include request module in node project?
var request = require('request');




Question: Give example of GET http call?
var request = require('request');
request('http://domain.com/ajax.php', function (err, response, body) {
   if (err) {
    return console.error('upload failed:', err);
  }
    console.log(body);  
});




Question: Give example of POST http call with parameter?
request({method:'post',url:'http://domain.com/ajax.php', form: {name:'hello',age:25},headers:options}, function (error, response, body) {  
    console.log(body);  
});




Question: How to send custom header with post method?
var headersOpt = {  
    'User-Agent': 'request'  
};
request(
        {
        method:'post',
        url:'http://domain.com/ajax.php', 
        form: {name:'hello',age:25}, 
        headers:headersOpt
    }, function (error, response, body) {  
        
        console.log(body);  
});




Question: How to set cookie with request?
request.cookie('key1=value1')




Wednesday 14 June 2017

mocha module with nodeJs tutorial

mocha module with nodeJs tutorial

Question: What is Mocha?
Mocha is a Rich JavaScript framework running on Node.js and in the browser making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.



Question: How to install Mocha?
npm install --global mocha



Question: How to test script with Mocha?
mocha tests.js



Question: How to check Success with Mocha?
Success
function add(a,b){
  return a+b;
}

   
//Success
it('should add two numbers-Success', () => {
  var res = add(33, 11);

  if (res !== 44) {
    throw new Error(`Expected 44, but got ${res}.`)
  }
});

Output
should add two numbers-Success passing (15ms)



Question: How to check Failure with Mocha?
function add(a,b){
  return a+b+2;
}

   
//Failed
it('should add two numbers-Success', () => {
  var res = add(33, 11);

  if (res !== 44) {
    throw new Error(`Expected 44, but got ${res}.`)
  }
});  


Output
1) should add two numbers-Failed 0 passing (25ms) 1 failing 1) should add two numbers-Failed: Error: Expected 44, but got 46. at Context.it (utils\utils.test.js:11:11)


Question: How to write Asynchronous code with Mocha?
describe('User', function() {
  describe('#save()', function() {
    it('should save without error', function(done) {
      var user = new User('Luna');
      user.save(done);
    });
  });
});



Question: How to write Synchronous code with Mocha?
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      [1,2,3].indexOf(5).should.equal(-1);
      [1,2,3].indexOf(0).should.equal(-1);
    });
  });
});




Question: How we can achieve HOOKS with Mocha?
describe('hooks', function() {
  before(function() { });
  after(function() {  });
  beforeEach(function() {  });
  afterEach(function() {});  
});



Question: What is Github URL for mocha?
https://github.com/mochajs/mocha


Question: In Which language mocha is written?
JavaScript



Question: What is offical website URL of Mocha?
https://mochajs.org/


Monday 12 June 2017

Node js Redis tutorial - Quick Start

Install redis in nodeJS, Make redis connection and stored data in redis, Get data from redis, update and delete the data from redis.

Question: How to install redis module with node?
npm install redis




Question: How to include redis in nodeJS Project?
var redis = require("redis");



Question: How to connect to redis with nodeJS?
var client = redis.createClient();

//On connection
client.on('connect', function() {
    console.log('connected');
});

//On error of connection
client.on('error', function() {
    console.log('error');
});



Question: How to Store data/Get Data/ Delete data in redis with nodejs?
Store single value
client.set('technology', 'NodeJS');

Get Stored value
client.get('technology');

Delete Stored value
client.del('technology', function(err, reply) {
    console.log(reply);
});



Question: How to check Stored value exist OR Not
client.exists('technology', function(err, reply) {
    if (reply === 1) {
        console.log('Stored in Redis');
    } else {
        console.log('Not Stored in Redis');
    }
});




Question: What is HMSET in nodeJS?
HMSET is like hset but it allow to store value in "key/value" paris.



Question: How to store data in key/value pairs in redis?
client.hmset('frameworks_list', {
    'javascript': 'AngularJS',
    'css': 'Bootstrap',
    'node': 'Express'
}, function(err, msg) {
    if (err) {
        console.log("Error During save the data");
    }
    //console.log(msg);//ok    
});




Question: How to get data which was stored with hmset redis?
client.hgetall('frameworks_list', function(err, msg) {
    if (err) {
        console.log("Error During save the data");
    }
    //console.log(msg);//{javascript: 'AngularJS', css: 'Bootstrap', node: 'Express' }
});



Question: How to store unique values in redis?
client.sadd(['emails', 'abc1@no-spam.ws', 'abc2@no-spam.ws', 'abc3@no-spam.ws'], function(err, msg) {
});



Question: How to get stored values which was set sadd with in redis?
client.smembers('emails', function(err, msg) {
    
});



Thursday 8 June 2017

How to Create RESTful APIs in Node Js using Express JS and MongoDB

How to Create RESTful APIs in Node Js using Express JS and MongoDB

Question: What is RESTful APIs?
Full form of REST is Representational State Transfer. It is web standards architecture used to create an API.


Question: What type of request handled by RESTful APIs?
HTTP requests


Question: How to create an API?
  1. Create a folder with name of api in your node project, and  create three folder inside this. i.e controllers, models and routes.
  2. Create 3 empty files in each folder i.e todoListController.js, todoListModel.js and todoListRoutes.js
  3. Now, Folder Structure will be as below:
  4. -api
        --api/controllers/todoListController.js
        --api/models/todoListModel.js
        --api/routes/todoListRoutes.js
  5. Add Following script in each empty file: todoListController.js
    var mongoose = require('mongoose'),
            Task = mongoose.model('Tasks');
    
    /* List all todoList*/
    exports.list_all_tasks = function(req, res) {
        Task.find({}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    /* List all todoList*/
    exports.create_a_task = function(req, res) {
        var saveData = {}
        saveData.name = req.body.name;
        saveData.status = req.body.status;
        var new_task = new Task(saveData);
        new_task.save(function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });    
    };
    
    /* Get a todo list details*/
    exports.read_a_task = function(req, res) {
        Task.findById(req.params.taskId, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    /* UPdate a toto data*/
    exports.update_a_task = function(req, res) {
        Task.findOneAndUpdate(req.params.taskId, req.body, {new : true}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    exports.delete_a_task = function(req, res) {
        Task.remove({
            _id: req.params.taskId
        }, function(err, task) {
            if (err)
                res.send(err);
            res.json({message: 'Task successfully deleted'});
        });
    };


    todoListModel.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var TaskSchema = new Schema({
        name: {
            type: String,
            Required: 'Kindly enter the name of the task'
        },
        Created_date: {
            type: Date,
            default: Date.now
        },
        status: {
            type: [{
                    type: String,
                    enum: ['pending', 'ongoing', 'completed']
                }],
            default: ['ongoing']
        }
    });
    
    module.exports = mongoose.model('Tasks', TaskSchema);
    


    todoListRoutes.js
    module.exports = function(app) {
        var todoList = require('../controllers/todoListController');
    
    
        // todoList Routes
        app.route('/tasks')
                .get(todoList.list_all_tasks)
                .post(todoList.create_a_task);
    
    
        app.route('/tasks/:taskId')
                .get(todoList.read_a_task)
                .post(todoList.update_a_task)
                .delete(todoList.delete_a_task);
    }; 


  6. Create a myapp.js empty file in project folder and add following script code.
    var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModel'),
    bodyParser = require('body-parser');
    
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/Tododb');
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    var routes = require('./api/routes/todoListRoutes');
    routes(app);
    
    app.listen(port);
    console.log('RESTful API server started: ' + port+' PORT');
    
  7. Now you need install following modules
    npm install express
    npm install mongoose
    npm install body-parser
    
  8. Now run following command, to test the APIs
    node myapp.js
    



Question: Provide Create Task API
URL: http://localhost:3000/tasks
Method: POST
Request Data:
{
"name":"I need to go for walk",
"status":"ongoing"
}



Question: Provide List All records API
URL: http://localhost:3000/tasks
Method: POST
Response Data:
[{"_id":"5937ff6a5fc96f1c1492877f","name":"I will go for walk daily.","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:28:10.608Z"},{"_id":"593803fb5fc96f1c14928782","name":"Get up early in the morning","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:47:39.246Z"}]



Question: Provide Update Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Request Data:
{  
  "name": "I goes on walk daily.", 
}



Question: Provide Get Records:
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Response Data:
{"_id":"5938d8e86d3e500cd8da6a12","name":"Arun kumar Gupta","__v":0,"status":["ongoing"],"Created_date":"2017-06-08T04:56:08.156Z"}



Question: Provide Delete Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: DELETE
Response Data:
{
  "message": "Task successfully deleted"
}



Tuesday 6 June 2017

How to use cookies with expressJS in node.js

How to use cookies with expressJS in node.js

Question: What is cookies in NodeJS?
Cookies is a node.js module for getting and setting HTTP(S) cookies.


Question: How to install cookies?
npm install cookie-parser       



Question: How to setup cookie with expressJS?
var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());
     



Question: What are the feature of cookie?
  1. Lazy: Since cookie verification against multiple keys could be expensive, So cookies are verified lazily.
  2. Secure: All cookies are httponly by default and cookies sent over SSL are secure by default.
  3. Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format.
  4. Agnostic: This library is optimized for use with Keygrip, but does not require it.



Question: How to set cookies?
app.get('/set-cook', function(req, res) {
       //Set the cookie
      var c_name='cookie_name';        
      res.cookie(c_name, 'cookie value');
      
      //Send Response
      res.send('cookie value');
});
Note above wll work with expressJs only.
Question: How to get cookies?
app.get('/get-cook', function(req, res) {        
    //Get cookie name
      var cookieValue=req.cookies.cookie_name; 

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to delete cookies?
app.get('/delete-cook', function(req, res) {        

    //Delete the cookie
     clearCookie(cookie_name);

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to set expiration time for cookie?
res.cookie(name , 'value', {expire : new Date() + 600}); //10 minutes

res.cookie(name , 'value', {expire : new Date() + 3600}); //1 hour

res.cookie(name , 'value', {expire : new Date() + 18000}); //5 hour



Question: What are HTTP cookies?
HTTP cookies are small pieces of data that are sent from a website and stored in your browser. With use of cookies we maintain the login and track the user activities. Cookies are very valuable to better user experience. Following are the three main use of cookies.
  1. Session management
  2. Personalization
  3. Track the user activites



Question: Why we must use Cookie-Free Domains for static contents?
Cookies are very useful in website. But while access static contents of website like CSS, image and JS then there is no use of cookie. Means while Browser is accessing the static file, Server should send the static content without use of cookie. It will improve the website performance.



Monday 5 June 2017

Mongoose Tutorial - listing records, Add Record, update record and delete record

mongoose tutorial - listing records, Add Record, update record  and delete record

Question: How to install the mongoose?
npm install mongoose



Question: How to update the mongoose?
npm update mongoose



Question: How to Start the mongoose?
Include the mongoose in the project
var mongoose = require('mongoose');

Make the Db connection with mongodb
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;

Check the Error OR Success on Db Connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});  




Question: How to Create Model with mongoose?
Here we have set the two fields only, you can add more if required.
var TodoSchema = mongoose.Schema({
  id: String, //datatype is string
  name: String, //datatype is string          
});       
var Todo = mongoose.model('Todo', TodoSchema);

In mongoose.model, the first argument is the singular name of the collection.
Mongoose automatically looks for the plural version with lowercase of your model name.
means for Todo, it will look todos.



Question: How to set unique key for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});



Question: How to set unique key and required for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true }, 
  email: { type: String, unique: true, required:true }, 
  name: String, //datatype is string          
});



Question: How to list the records from mongodb?
var cursor = Todo.find({ }).cursor();
cursor.on('data', function(doc) {
    jsonData[doc.id] = doc.name;  
});
cursor.on('close', function() {
    console.log(jsonData);                   
});



Question: How to save the record?
var TodoDetails = new Todo({ id: "10",name:"this id test message"});
TodoDetails.save(function (err) {if (err) console.log ('Error on save!')});        



Question: How to update the record?
 Todo.update({id: "10" }, { $set: { name: "this is update message" }}, {}, function(){
             console.log("Update the records successfully");
        })



Question: How to delete the record?
    Todo.find({ id:"10" }).remove( function(){
     console.log("Record deleted successfully");
    }); 



Question: How to delete the document and check is it deleted?
Todo.find({ id:"10" }).remove( function(err, effectedRows){
    if(err){
         console.log("Unable to delete the record");
    }
    if(effectedRows.n==0){
        console.log("Zero Record deleted");
    }else{
        console.log("Record deleted successfully");
    }
     
 }); 



Question: What are the difference between mongoose.model and mongoose.Schema?
Model is an object that gives you easy access to a collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.

Schema is an object that defines the structure of the documents that will be stored.
it enables you to define types and validators for all data.



Question: How to get first record(s) from listing?
Todo.findOne({ 'name': 'kumar' }, 'id', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          

})        



Question: How to fetch specific column?
  Todo.find({ 'name': 'kumar' }, 'id name', function (err, person) {
          if (err) return handleError(err);
            //console.log(person);          
             res.send(person);
        })



Question: How to limit the number of records?
You can use limit method.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3);



Question: How to get listing by name in ascending order?
You can use sort method, -1 means descending order, 1 means ascending order.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: How to use "in" in where clause?
Todo.find({ name: { $in: ['arun', 'gupta']}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: Give full Query example?
Todo.find({ 
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    name: { $in: ['technology', 'web'] }

}, 'id name', function (err, person) {
  if (err) return handleError(err);
    //Here will be display all the records
    console.log(person);               
}).limit(3).sort({ name: -1 });




Question: How to create custom function in mongoose.model?
In schema/Model file (Create a custom function)
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});
TodoSchema.statics.findByIdTest = function (todoId,cb) {
  return this.model('Todo').find({ id: todoId }, cb);
};

How to use controller file.
Todo.findByIdTest(2677,function(error, data){
    console.log(data);    
});




Tuesday 30 May 2017

What is mongoose? How to use mongoose with nodejs for mongodb?

What is mongoose? How to use mongoose with nodejs for mongodb?
 How to use mongoose with nodejs for mongodb?

Question: What is mongoose in node js?
mongoose is an object modeling package for Node that essentially works like an ORM.


Question: How to install mongoose in node js?
npm install mongoose



Question: What is the --save option for npm install?
When we do "npm install", then it install the modules.
If we need to update the version of module in package.json, then we have to do it manually.
BUT when we do "npm install --save", then it install the modules and update the package.json automatically.


Question: What is difference between dependencies and devDependencies?
dependencies are modules your project depends on, devDependencies are modules you use to develop your project.

Examples of dependencies are request, through2 and concat-stream.
Examples of devDependencies are grunt, mocha, eslint, tape, and browserify.


Question: How to connect to MongoDB database?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongodb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});


Question: How to define the Schema in mongoose?
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});



Question: How to compile the Schema with model?
var User = mongoose.model('User', userSchema);
module.exports = User;
Here User inside "mongoose.model" is a User model, where all the data will be managed.
var User is an Model Object which will be used to process on the document.



Question: What are different type of data types in mongodb?
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array


Question: How to add a record in document with model?
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails); 



Question: How to add a record in document with model with FULL CODE?
//include the js
var mongoose = require('mongoose');

//database connection
mongoose.connect('mongodb://localhost:27017/mongodb');

//Create schema
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});

//create User Object
var User = mongoose.model('User', userSchema);

//Save User details in database
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails);



Question: How to fetch all records?
User.find({}, function(err, users) {
  if (err) {throw err;}
  console.log(users);
});



Question: How to fetch one record?
User.find({ username: 'testuser' }, function(err, user) {
  if (err) throw err;

  // object of the user
  console.log(user);
});



Question: How to update record?
        User.update({username: 'testuser' }, { $set: { name: "New name" }}, {}, function(){
            //here comes after update the record
        })



Question: How to delete record?
  User.find({ username: 'testuser'  }).remove( function(){
  //write here your code after delete
 }); 



Monday 29 May 2017

Angularjs 2 Interview Questions and Answers

Angularjs 2 Interview Questions and Answers


Question: Why AngualrJS2 over AngualrJS1?
  1. Angular 2 is simpler and faster than Angular 1.
  2. You can update the large data sets with minimal memory overhead.
  3. It will speed up the initial load through server side rendering.



Question: What are the feature of AngualrJS2?
  1. Angular 2 is faster than Angular 1
  2. Angular 2 is easier than Angular 1
  3. It supports old browsers also including IE9+ and Android 4.1+.
  4. It is a cross platform framework.
  5. Angular 2 is mainly focused on mobile apps.
  6. Code structure is very simplified than the previous.



Question: How to install AngualrJS2 in NodeJS?
  1. Create an folder and go inside that folder using command line.
  2. Create en empty file package.json and add following contents.
    {
      "name": "angular2-demo",
      "version": "1.0.0",
      "scripts": {
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lite": "lite-server",
        "typings": "typings",
        "postinstall": "typings install"
      },
      "license": "ISC",
      "dependencies": {
        "angular2": "2.0.0-beta.7",
        "systemjs": "0.19.22",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.2",
        "zone.js": "0.5.15"
      },
      "devDependencies": {
        "concurrently": "^2.0.0",
        "lite-server": "^2.1.0",
        "typescript": "^1.7.5",
        "typings":"^0.6.8"
      }
    }
  3. Create an empty file tsconfig.json and add following contents.
    {
      "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
      ]
    }
  4. Create an empty file typings.json and add following contents.
    {
      "globalDependencies": {
        "core-js": "registry:dt/core-js",
        "jasmine": "registry:dt/jasmine",
        "node": "registry:dt/node"
      }
    }
  5. Execute following command from command line.
    npm install

Monday 24 April 2017

Node.js - Global Objects

Node.js - Global Objects

Question: How to display the current filename?
console.log(__filename);
This gives you local filename of the current module.



Question: How to display the current directory name?
console.log(__dirname);
This gives you local dirname of the current module.



Question: How to call a function after 5 seconds?
For this, you can use a global function i.e setTimeout.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call after 5 seconds*/
setTimeout(helloFunction, 5000);



Question: How to stop calling a function which was started with setTimeout?
For this, you can use a global function i.e clearTimeout.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call after 5 seconds*/
var funcObj=setTimeout(helloFunction, 5000);

//stop funtion
clearTimeout(funcObj);



Question: How to call a function in every 7 seconds?
For this, you can use a global function i.e setInterval.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call in every 7 seconds*/
setInterval(helloFunction, 7000);



Question: How to stop calling a function which was started with setInterval?
For this, you can use a global function i.e clearInterval
clearInterval(funcObj);



Question: What are different Console Methods to print info, error, warning etc?
  1. console.log: Prints to stdout with newline.
  2. console.error: Prints to stderr with newline.
  3. console.dir: Uses util.inspect on obj and prints resulting string to stdout.
  4. console.time: Mark the time
  5. console.timeEnd: Mark the time end
  6. console.trace: Print to stderr Trace



Question: What are Process Events?
The process object is a global object and can be accessed from anywhere.
process.on('exit', function(code) {   
   console.log('About to exit with code:', code);
});
console.log("Program Ended");



Question: What are different the Process Events?
  1. exit
  2. beforeExit
  3. uncaughtException
  4. Signal Events


Wednesday 22 March 2017

Express js Interview questions and answers

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.
npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage"); //Shown in console
   res.send('This is GET Method for Homepage'); //Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
   console.log("Got a POST request for the user_list URL"); //Shown in console
   res.send('This is POST Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
   console.log("Got a POST request for the add_user URL"); //Shown in console
   res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
   console.log("Got a GET request for the user_list URL"); //Shown in console
   res.send('This is GET Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
   console.log("Got a GET request for /ab*");
   res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {                    
          console.log(res);
          console.log(body);
      });




Question: How to post data and get in express Js?
HTML Code

<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" />  <br />
Email: <input name="email" type="text" />
         Phone: <input name="phone" type="text" />
         <input type="submit" value="Submit" />
      </form>


Express JS Code
app.get('/register', function (req, res) {   
   response = {
      name:req.query.name,
      email:req.query.email
      phone:req.query.phone
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
   res.send('Hello ');
});
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code

<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />         
         <input type="submit" value="Submit" />
      </form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);   
   var destinationFile = __dirname + "/images/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(destinationFile, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully in '+destinationFile,
                  filename:req.files.file.name
               };
            }
         //console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: How to setup the images and access them?
Add Following code in my server.js (OR main file).
app.use(express.static('public'))
Now, you can add images in public folder and can access like below:
http://localhost:3000/1.jpg
http://localhost:3000/2.jpg
http://localhost:3000/3.jpg



Question: How to do increment the value by 1?
 User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();



Question: How to do decrement the value by 1?
 User.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();