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

Tuesday 11 July 2017

Express JS Interview Questions and Answer for experienced

Express JS Interview Questions and Answer for experienced

Question: What is meaning of app.get(*) in express js?
app.get(*) means that for any GET request not already handled yet, will come in this route.
Note: this must be at the end of all route handling (Last route).

See example below:
//Login route
app.get('/login', function(req,res){ /*Login code */ });

//Register route
app.get('/register', function(req,res){/*Register code */});

//Route which is not handled yet
app.get('*', function(req, res, next) {
  var err = new Error();
  err.status = 404;
  next(err);
}

As we know, last route is for not found route, So in this we have set the status 404.
and pass the error object to the next.
When we call next() without parameter, then it run next middleware.
When we call next() with parameter, then it run differently.


Question: What is use of next() in express JS?
next is an argument provided by Express.js as a way to "pass along" control to the next middleware (or route).


Question: What is Middleware?
Middleware are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.
The next middleware function is commonly denoted by a variable named next.


Question: What are benefits of Middleware?
  1. Execute any code.
  2. Make changes to the request and the response objects.
  3. End the request-response cycle.
  4. Call the next middleware function in the stack.



Question: What are different Middleware?
  1. Application-level middleware
    app.use(function (req, res, next) {
      console.log('Time:', Date.now())
      next()
    })
  2. Router-level middleware
  3. Error-handling middleware
  4. Built-in middleware
  5. Third-party middleware



Question: How to setup log4js?
Install log4js
npm install log4js

Include log4js
//include the log4js file
var log4js = require('log4js');

Configure log4js
//Configure the log4js
log4js.configure({
  appenders: { 
      display: { type: 'stdout' },
      file: { type: 'file', filename: './data/chat_logs.log' }
  
    },
  categories: { 
      display: { appenders: ['display'], level: 'debug' },      
      file: { appenders: ['file'], level: 'debug' },
      default: { appenders: ['display'], level: 'debug' }
      
  }
});

Display log4js in console
var Logger = log4js.getLogger('display'); 

Logger.trace('this is message1');
Logger.info('this is message2');
Logger.warn('this is message3');
Logger.error('this is message4');
Logger.debug('this is message5');
All the data will display in console


Question: How to store the logs in file?
var Logger = log4js.getLogger('file'); 

Logger.trace('this is message1');
Logger.info('this is message2');
Logger.warn('this is message3');
Logger.error('this is message4');
Logger.debug('this is message5');




Friday 7 July 2017

Mongoose iterate records over results using async module

Mongoose iterate records over results using callback functions

Download the async module in nodeJs Project?
npm install async --save



Inculude the module in NodeJS?
async= require('async');



Following are code snippet example which demostrate, how to update the listing?
app.get("get_chat_messages", function(req, res) {
    var vid = req.query.vid;
    
    //Get the records from mongoose
    AjaxChatMessage.find({vid: vid}, function(err, items) {

    //initalize vars
    var index
    var results={}

    //include the module
    async= require('async');

    //iterate records
   async.each(items,     
     function(item, callback){  
         index=items.indexOf(item);
         results[index]={};
         results[index].text=item.text;
         results[index].vid=item.vid;
         results[index].user_display_name=item.user_display_name;
         results[index].id=item.id;
         results[index].photo=item.user.photo;
         results[index].logintype=item.user.logintype;
         
       if((items.indexOf(item)+1)==items.length){
           res.send(results);
       }
     });
     
    }).sort({id: 1}).populate('user');
}



Thursday 6 July 2017

Node Js Interview Questions and answer for Experienced

Node Js Interview Questions and answer for Experienced

Question: What is objectId in MongoDB?
It is 12 byte object consist of following
  1. a 4-byte value representing the seconds since the Unix epoch
  2. a 3-byte machine identifier
  3. a 2-byte process id
  4. a 3-byte counter, starting with a random value.



Question: How to get timestamp from objectId?
ObjectId.getTimestamp();



Question: What is difference between npm install vs npm update?
npm install:
1. installs all modules that are listed on package.json file and their dependencies.
2. module without version mention in package.json, npm install will be ignore if already installed.

npm update:
1. updates all packages in the node_modules directory and their dependencies.
2. module without version mention in package.json, will update to latest version (If not then installed the latest version).


Question: How to set npm start with start the application?
  1. Open package.json which is located on root.
  2. Add following code in package.json (If not added)
      "scripts": {
        "start": "node index.js"
      }
    

    Please repace "index.js" with your application file.
  3. Now, you can run npm start from command console.



Question: How to destroy the session in node?
You can use req.session.destroy(), See Exampe below:
exports.logout = function(req, res) {        
    req.session.destroy();
    res.send({logout:1});
}



Question: How to redirect to 404 errors page in ExpressJS?
After difining all the URL route, add the following code
app.use(function(req, res, next) {
    res.status(404).json({errorCode: 404, errorMsg: "route not found"});
});

When someone trying to access not available pages, it will show 404 error code.


Question: What is CORS?
Cross Origin Resource Sharing.


Question: What use use of CORS?
Suppose your are website is at mywebiste.com and want to access the javascript/API which is on mywebiste2.com. You can't access the data/api from mywebiste2.com unless they allow you. This is known as Cross Origin Resource Sharing.


Question: How we can achieve CORS?
Add the following code in your node application, it will allow everyone to access your code. In Access-Control-Allow-Origin, you can specify the domain name.
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});



Question: What do you mean by Asynchronous API?
All APIs of Node.js library are aynchronous, means all are non-blocking.


Question: What is package.json?
package.json is present in the root directory of any Node application/module and is used to define the properties of a package.


Question: What is Piping in Node?
Piping is a mechanism to connect output of one stream to input of another stream. It means get data from one stream and to pass output of that stream to another stream and there is no limit to piping operations.


Question: What is Callback in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Node is single thread based application and works on the behalf of events.


Wednesday 5 July 2017

Emoji / Emotions icons integration in CHAT

emoji/emotions icons integration in existing chat

Hello Users,
Here, I will give an example to integrate the emoji/emotions icons in your Chat . Its done for node based chat, but still you can use for Ajax based chat.
 Its quite simple, you just need to replace the emotions code to images.
 For Example
:) - Happy
:( - Sad

Whenever new message appear, then you need to replace the smiley code to images OR previous message need to replace the smiley code to corresponding image.

Follow the Below Simple steps to Integrate in CHAT.


  1. Step1: Download imoji icons from following links:
    https://drive.google.com/open?id=0BxKVas2R9pKlYmo2eHEtbjMtRk0

    place all image in \public\images\emoticons
  2. Setup the static images path in express JS project.
        var express = require('express');
        var app = express();
        var http = require('http').Server(app);
    
        //set the public path
        app.use(express.static('public'));
        
  3. In Client side, display the empotions
    JavaScript functions to convert the code to smiles
    
        function replaceTextwithAllowedEmojis(text){        
                var returnText = text;
                //Emotions
                var emoticonCodes = [':)',':(',';)',':P',':D',':|',':O',':?','8)','8o','B)',':-)',':-(',':-*','O:-D','>:-D',':o)',':idea:',':important:',':help:',':error:',':warning:',':favorite:'];
                
                //Emoji iconds
                var emoticonFiles = ['smile.png','sad.png','wink.png','razz.png','grin.png','plain.png','surprise.png','confused.png','glasses.png','eek.png','cool.png','smile-big.png','crying.png','kiss.png','angel.png','devilish.png','monkey.png','idea.png','important.png','help.png','error.png','warning.png','favorite.png'];
    
                var emojiHtmlStrPrefix = '<img class="emoticon" src="/images/emoticons/&#39;;
                var emojiHtmlStrPostfix = &#39;" />';
                
               
                for(var i=0; i<emoticoncodes .length="" emoticoncodes="" i="" if="" returntext.indexof=""> -1)){
                        // replace text with its icon file
                        var imgHtmlStr =  emojiHtmlStrPrefix+emoticonFiles[i]+emojiHtmlStrPostfix;
                        returnText = returnText.replace(emoticonCodes[i],imgHtmlStr);
                    }
                }
                return returnText;
        }
    </emoticoncodes>
  4. Display the above functions.
    
                socket.on('chat_message', function(dataObj) {                
                    $('#messages').append($('
    [li]').html(replaceTextwithAllowedEmojis(dataObj.text)));
                });
    



Monday 3 July 2017

Express Js routing example - GET/POST/PUT

Express JS Routing - Understanding GET/POST/PUT with parameter

Question: Give example of express JS working with Node?
var express = require('express');
var app = express();

var bodyParser = require('body-parser')
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);  
});
app.listen(3000);



Question: What is use of body-parser?
It is middleware in nodeJS.
body-parser is used to parse incoming request bodies, available under the req.body property.



Example-1: URL / with Get Method.
app.get('/', function (req, res) {
  res.send('Hello, this is Home page.')
})



Example-2: URL /about with Get Method.
app.get('/about', function (req, res) {
  res.send('You have called /about with get method.')
})



Example-3. URL /senddata with POST Method.
app.post('/senddata', function (req, res) {
    //req.body have all the parameter
   console.log(req.body);
  res.send('Hello, Received post data request.')
})



Example-4: Routing with Regex 
app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

This route path will match acd, abcd.


Example-5: Routing with Regex
app.get('/ab+cd', function (req, res) {
  res.send('ab?cd')
})
This route path will match abcd, abbcd, abbbcd, and so on.



Example-6: Routing with dynamic parameter 
app.get('/users/:userId/books/:bookId', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /users/10/book/12222');
});

Request URL: http://localhost:8080/users/10/books/12222


Example-7: Routing with dynamic parameter - Example 2
app.get('/messages/:from-:to', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /messages/10-100');
});

Request URL: http://localhost:8080/messages/10-1000


Question: How to send request with all methods i.e GET/POST/PUT
app.all('/messages/list', function (req, res) {  
   res.send('Work for all type of request');
});



NodeJS - call a method after another method is fully executed

NodeJS - call a method after another method is fully executed

Calling a function with callback method
delete_chat_message(messageId,function(result){            
    if(result.success){
        console.log('Chat message is deleted successfully.');
    }else{
        console.log('Unable to delete Chat message.');
    }
});


Function Definition with callback execution
    delete_chat_message=function(messageId, calbackFunc){
    var results = {success: 0, id: messageId}
    
        /* Model to delete the chat message*/
        AjaxChatMessage.remove({id: messageId}, function(err, data) {
            console.log('here');
            if (err) {
                results.success = 0;
            }else{
                results.success = 1;
            }
            //call the callback function
            calbackFunc(results);
        }); 
    }


Thursday 29 June 2017

How to upload file/images using nodejs?

How to upload file using nodejs?

I am assuming you already have install NodeJS in your System, Just follow below simple steps


Install below module ?
npm install express
npm install fs
npm install body-parser
npm install multer



HTML Part?
Create a file upload.html and add below code in file.

        <form action="http://127.0.0.1:8081/file_upload" enctype="multipart/form-data" id="uploadForm" method="POST" onsubmit="return uploadForm()">
Upload File: <input name="file" size="50" type="file" />
            <br />
<input type="submit" value="Upload File" />
        </form>




Node JS Code create upload.js file and add below code.
var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: './tmp' });

app.get('/upload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "upload.html" );
})

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

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})



Question: Following are sample of file object in ?
 { fieldname: 'file',
  originalname: 'Desert.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './tmp',
  filename: '3570feafa527690b90b972a1bf085bdd',
  path: 'tmp\\3570feafa527690b90b972a1bf085bdd',
  size: 845941 }


Create following empty folder?
/tmp
/public
/public\upload



Now Start the Node project?
node upload.js



Access the Web URL?
http://127.0.0.1:8081/upload.html



Select the File and click on Upload File?
It will show below simiar message
{"message":"File uploaded successfully","filename":"Desert.jpg"}
Question: What port we have used here?
We have used 8081 port, but you can change it by change in upload.js

Wednesday 28 June 2017

What is a promise and how to use with mongoose?

What is a promise and how to use with mongoose?

Question: What is a promise?
A promise is an abstraction for asynchronous programming.
It's an object that proxies for the return value thrown by a function that has to do some asynchronous processing.


Question: How does promise work?
The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error)


Question: Give example of promise work in mongoose?
User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();
Here execute multiple function in one line is promise.


Question: How to setup mongoose with promise?
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/dbname');
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 Add the data in mongoDb with mongoose?
//Ajax chat messages
var AjaxChatMessageSchema = mongoose.Schema({
    id: Number,
    userID: Number,
    userName: String,
    userRole: String,
    channel: String,
    dateTime: String,
    ip: String,
    text: String,
    status: String,
    vid: Number
}, {collection: 'ajax_chat_messages'});
var AjaxChatMessage = mongoose.model('ajax_chat_messages', AjaxChatMessageSchema);

var saveData={id:11, userName:'testuser',text:'hello user'}
var AjaxChatMessageDtls = new AjaxChatMessage(saveData);
AjaxChatMessageDtls.save(function(err) {
    if (err) {
        console.log("Error while saving the details");
        response.success = 0;
        res.send(response);
    } else {
        response.success = 1;        
        res.send(response);
    }
});



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



Question: From where we can read more about promise?
http://mongoosejs.com/docs/promises.html


Thursday 22 June 2017

Express JS - use res.sendFile - use EJS template - Set and Get Session data

setup of EJS template in Express? Get/Set session in Express? How to setup static path in Express

Question: What is res.sendFile() in NodeJS?
It is a simple way to deliver an HTML file to the client.

Example of sendFile
var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);



Question: How to use EJS in Express?
Install the EJS
npm install ejs --save  

Set the Engine as EJS in node server
app.set('view engine', 'ejs');  

render file from node server
app.get('/', function(req, res) {  
  res.render('index', { title: 'The index page!' })
});

Use the parameter in File
<%= title %>



Question: How to Get/Set session in Express?
install session
npm instal express-session --save
Initiaization the session
var session = require('express-session');
app.use(session({
    secret: 'SECRETKEY',
    name: 'SESSION NAME',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));
Set the Session
var sessionData
app.get('/set-the-session', function(req, res) {    
    sessionData = req.session;
    var userDetails = {}    

    //set the session
    sessionData.isLogin = 1;
    sessionData.name = req.body.name;
    sessionData.email = req.body.email;
});
Get the Session
app.get('/get-session', function(req, res) {    
    sessionData = req.session;
    userDetails.isLogin = sessionData.isLogin;
    userDetails.name = sessionData.name;
    userDetails.email = sessionData.email;
    res.send(userDetails);    
});


Question: How to setup static path in Express?
var express = require('express');
var app = express();
app.use(express.static('public'))

create file in : images/kitten.jpg, Now you can access
http://localhost:3000/images/kitten.jpg


Question: Session is not working with ajax call
Explanation
URL: http://127.0.0.1:8080/getphotoaccess?uid=7177
When running in browser, session is working fine.
When running with ajax call, session is not working

Solution
You need to add xhrFields: {: true},in ajax request.
For Example:
$.ajax({
    type: "GET",
    url: "getphotoaccess?uid=7177",            
    dataType: "json",    
    xhrFields: {
            withCredentials: true
       },            
    success: function(resData){

    }
});




Tuesday 20 June 2017

Socket.IO module with nodeJs tutorial

How to send message from Node(server) to browser(client) and vice versa? How to connect/disconnect to  the room.

Question: What is socket.io module?
Socket.IO is a JavaScript library for realtime web applications.
It enables realtime, bi-directional communication between web clients and servers.
It has two parts
a) client-side library that runs in the browser.
b) server side that run in browser.



Question: Give example of real time application?
  1. Instant messengers like facebook notification/message.
  2. Push Notifications like when someone tags you in a picture on facebook, you receive an instant notification.
  3. Collaboration applications like multiple user editing same file.
  4. Online gaming




Question: Why we use socket.io?
  1. bi-directional communication channel between a client and a server.
  2. When an event occur, socket get notify and let to know the single client OR all clients.
  3. It is trust application and used by Microsoft Office, Yammer, Zendesk, Trello, and numerous other organizations.



Question: How to install socket.io in Web and Server?
In Browser (client)
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

In NodeJS
npm install socket.io

var io = require('socket.io')




Question: How get to know, if user is connect/disconnect?
In Server(Node)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

//Whenever someone connects (execute when come in Web page)
io.on('connection', function(socket){
  console.log('A user connected');

  //Whenever someone disconnects (execute when Leave the web page)
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

In Browser
 var socket = io.connect('http://127.0.0.1:3000'); 



Question: How to get to know, when new user comes in browse?

OR
Question: How to send message from Client(Browser) to Server(Node)?
In Server
 
socket.on('adduser', function(name, email, uid) {
    //name, email, and uid of user
    console.log('New user comes in web page');
});

In Browser>
 
socket.emit('adduser', 'Robin Sharma','robinsharma@no-spam.ws',2555);      




Question: How to send message from Server(Node) to Client(Browser)?
In Server
socket.emit('newRequestCome', 'name','myself send request'); //Send message to socket (Same window)
socket.broadcast.to(roomName).emit( 'newRequestCome','name','message'); //Send message to all socket (Other windows in same Room)

In Browser
 
socket.on('newRequestCome', function(name, message) {                        

});


Question: How to join the room and send message?
Join the room
io.on('connection', function(socket){
  socket.join('someNo12');
});



Question: How to send message the room?
Send message to the room
io.in('someNo12').emit('some event');
//io.to('someNo12').emit('some event');



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) {
    
});