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

Wednesday, 16 May 2018

Node Js Interview Questions and answer for 2 year experienced

Node Js Interview Questions and answer for 2 year experienced

Question: What is JSON.stringify()?
JSON.stringify() method converts a JavaScript object to a JSON string.
Following are three parameter of JSON.stringify.


Value (required): The value to convert to a JSON string.
replacer (optional): A function that alters the behavior of the stringification process, or an array of String and Number objects.
space (optional): A String or Number object that's used to insert white space into the output JSON string for readability purposes.



Question: Give example of JSON.stringify()?
JSON.stringify({});                    // '{}'
JSON.stringify(true);                  // 'true'
JSON.stringify('foo');                 // '"foo"'
JSON.stringify([1, 'false', false]);   // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({ x: 5 });              // '{"x":5}'



Question: What is JSON.parse()?
JSON.parse() method converts JSON string to JavaScript object.


Question: What is arrow function?
An arrow function expression has a shorter syntax than a regarular function and does not have its own this, arguments, super, or new.target.


Question: Give example of arrow function?
var materials = [
  'Hydrogen',
  'Helium',
  'Beryllium'
];
console.log(materials.map(material => material.length));// expected output: Array [8, 6, 9]


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS. We give the data from node and same used in the handlebar template.



Question: How to configure handlebar?
const hbs = require('hbs');
app.set('view engine', 'hbs');

Now you can place the html files in view folder with extension of .hbs



Question: How to pass the data to handlebar engine and used in view file?
Pass parameter
app.get('/aboutus', (req, res) => {
  res.render('home.hbs', {
    pageTitle: 'About Page Title',
    welcomeMessage: 'Welcome'
  });
});

aboutus.hbs (Use with variable name enclosed with double curly braces)
{{pageTitle}} //About Page Title
{{welcomeMessage}} //Welcome



Question: How to create element(partial) file in handlerbar ?
In node server file, set the following
hbs.registerPartials(__dirname + '/views/partials');

You can call a comman file from another file with following system
{{> header}}

Here header file path is /views/partials/header.hbs


Question: What is an error-first callback?
Error-first callbacks are used to pass errors and data. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong.
fs.readFile(filePath, function(err, data) {  
  if (err) {
    // handle the error, the return is important here
    // so execution stops here
    return console.log(err)
  }
  // use the data object
  console.log(data)
})



Question: What are Promises?
The Promise object represents the event completion or failure of an asynchronous operation, and its resulting value.
function readFile(filename, enc){
  return new Promise(function (resolve, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else resolve(res);
    });
  });
}



Question: What's a stub? Name a use case?
Stubs are functions that simulate the behaviors of components/modules.
Stubs provide canned answers to function calls made during test cases.
var fs = require('fs')

var writeFileStub = sinon.stub(fs, 'writeFile', function (path, data, cb) {  
  return cb(null)
})

expect(writeFileStub).to.be.called
writeFileStub.restore();



Question: What is callback hell in Node.js?
Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain.


Question: What is the role of REPL in Node.js?
Full form of REPL is REPL Read Eval print Loop.
The REPL in Node.js is used to execute ad-hoc Javascript statements.



Question: Name the types of API functions in Node.js?
Blocking functions In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously.

Non-Blocking functions
In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.


Tuesday, 6 February 2018

Node Js Buffer module examples with script code

Node Js Buffer module examples with script code

Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers. Buffer class is a global class that can be accessed in an application.


Question: How to create an empty buffer object?
var bufferData=Buffer.alloc(1024); //1024 bytes



Question: How to write in buffer object?
var bufferData.write('this is string'); //write only string



Question: How to create an array of buffer?
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
console.log(bufferData);//

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
console.log(arrayObject);



Question: What is concat? How to concate the buffer data?
Concatenates an array of Buffer objects into one Buffer object
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
bufferData=Buffer.concat(bufferData);

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
bufferData=Buffer.alloc(1024);
bufferData = Buffer.concat(arrayObject);
console.log(bufferData);



Question: How to compare two buffer?
var buf1 = Buffer.from('abc');
var buf2 = Buffer.from('abc');
var compare1 = Buffer.compare(buf1, buf2);
console.log(compare1); //0

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var compare2 = Buffer.compare(buf1, buf2);
console.log(compare2); //-1

var buf1 = Buffer.from('b');
var buf2 = Buffer.from('a');
var compare3 = Buffer.compare(buf1, buf2);
console.log(compare3); //1



Question: How to check if data is buffer?
Buffer.isBuffer(obj);//true|false



Friday, 22 September 2017

Nodejs Interview Questions and Answer 1 year Experience

Nodejs Interview Questions and Answer 1 year Expereince

Question: How do I include a JavaScript file in another file?

Suppose you have following file with hello.js which you want to include.
export function hello() {
  return "Hello, How are you?";
}

Use following syntax to include hello.js?
const helloFileObj = require('./hello');
console.log(helloFileObj.hello()); //It would print Hello, How are you?



Question: What's the difference between tilde(~) and caret(^) in package.json?

the tilde(~) matches the most recent minor version.
For Example ~1.4.3 will match all 1.4.x versions but will miss 1.5.0.
Benefits: Gives you bug fix releases.

the caret(^) matches the most recent major version.
For Example ^1.4.3 will match all 1.x.x versions including 1.5.0 but will hold off on 2.0.0
Benefits: Gives you bug fixes including new functionalities.



Question: How do I pass command line arguments?
node server.js one two=222 three
Here one, two=222 and three are command line arguments (1,2,3 respectively).

Following are way to access argument process.argv is array containing the command line arguments
Following are the output when we print process.argv
Script to print the arguments


Output
0: node
1: server.js
2: one
3: two=222
4: three



Question: How to access 2nd argument when passed in command line?
process.argv.slice(3,4); //two=222



Question: How to list the packages?
List Local packages?
npm list

List Global packages?
npm list -g

Question: How to exit from node Code?
process.exit()



Question: Read environment variables in Node.js?
process.env.ENV_VARIABLE



Question: How to generate Secure random token Node.js?
For this you can use crypto module in nodeJS.
require('crypto').randomBytes(48, function(err, buffer) {
  var token = buffer.toString('hex');
});



Question: How to output pretty html in Express?
app.locals.pretty = true;



Question: How to clean node_modules folder of packages that are not in package.json?
app.locals.pretty = true;



Question: How to format a date string in UTC Format?
  
new Date().toISOString(); //2017-09-04T14:51:06.157Z

  
new Date().toISOString().
  replace(/T/, ' ').      // replace T 
  replace(/\..+/, ''); //2017-09-04 14:55:45 



Question: How to get client IP Address in Node JS?
  
app.get(/save-data, function (req, res){
    var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;   
    console.log(ipAddress); //will print the ip address of client
});



Question: How to force strict mode in node?
Write below code at the top of node file with enclosed with double quote.
 
use strict;


Question: What is promises in node js?
We use the promises for asynchronous operation and it have following 3 states.
  1. Pending
  2. Resolved
  3. Rejected



Question: What is promises in node js?
var somePromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Operation completed');
    // reject(Operation Failed');
  }, 2500);
});

somePromise.then((message) => {
  console.log('Success: ', message);
}, (errorMessage) => {
  console.log('Error: ', errorMessage);
});


Promise contain two parameter i.e. resolve(for success), reject(for failed).


Question: What is Yargs?
Yargs helps to parsing arguments of command line tools.


Question: How to install Yargs module in node?
npm i yargs --save


Question: Give example of Yargs module?
const argv = require('yargs').argv
console.log(argv.name);//Arun
console.log(argv.age);//28
console.log(argv.city);//Chandigarh

How to pass arguments
node test.js --name="Arun" --age="28" --city="Chandigarh"




Tuesday, 12 September 2017

How to create an HTTPS server in Node.js?

How to create an HTTPS server in Node.js?

Question: Run Node with http?
var express = require('express');
var app = express();

//Include modules
var http = require('http').Server(app);
var io = require('socket.io')(http);


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

You can run as http://localhost:8082


Question: What certificate you require for https?
  1. server.key
  2. server.crt
  3. Create a folder public/cert at root of your project and add above 2 files.



Question: Run Node with https?
var express = require('express');
var app = express();

//Include modules

var https = require('https');
fs = require('fs');


var privateKey = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);

httpsServer.listen('8083', function() {
    console.log('https listening on *:8083');
});
 

You can run as https://localhost:8083



Tuesday, 8 August 2017

Send Acknowledgment for socket.io event

Send Acknowledgment for socket.io event

Question: How to send Acknowledgment for socket.io event?
in node.js (Server side)
io.sockets.on('connection', function(socket){    

    /* Message Received from Client*/
    socket.on('chat_messsage', function(data, callback){        
        var responseData = { 'message':data.message, 'received':1};        
        callback(responseData); //Send Acknowledgment to the client
    });


});

Client Side JavaScript
var socket = io.connect('http://localhost:3000');
socket.on('connected', function (data) {    
    
    //Send message to Server with callback function
    socket.emit('chat_messsage', {message:"this is message"}, function(response){
        console.log(response); //console the Acknowledgment
    });

});



Question: How to Send additional data on socket connection?
Client side, connect with parameter
  var socket =  io.connect(chatURL,{ query: "req_from=browser" });


Sever side, Detect the client Connection.
io.on('connection', function (socket) {
  console.log(socket.handshake.query['req_from']);
});


Question: How to connect node with http and https?
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('cert/server.key', 'utf8');
var certificate = fs.readFileSync('cert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

//http connect
httpServer.listen(8080);
//https connect
httpsServer.listen(8443);



Tuesday, 18 July 2017

node js underscore tutorial with examples

node js underscore tutorial with examples

Question: How to install underscore in nodeJS?
npm install underscore





Question: How to include underscore in nodeJS?
var _ = require('underscore');





Question: What is map in underscore? How to use? Give example?
Produces a new array of values by mapping each value in list through a function. The iterates is passed three arguments: the value, then the index (or key) of the iteration, and reference.


console.log(_.map([1, 2, 3], function(num){ return num * 2; })); //2, 4, 6
console.log(_.map([1, 2, 3], function(num){ return num * 3; })); //3,6,9



Question: Give an example of underscore.each?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: How to check if variable is empty OR Not?
_.isEmpty({});//true
_.isEmpty({'1'});//false



Question: How to create range values?
_.range(6);//[1,2,3,4,5,6]



Question: Can we use underscore for Web Client?
Yes, for this you need to include following JS.
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js



Question: What are collections available in underscore?
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: What are array are available in underscore?
first
initial
last
rest
compact
flatten
without
union
intersection
difference
uniq
zip
unzip
object
indexOf
lastIndexOf
sortedIndex
findIndex
findLastIndex
range



Question: What functions are available in underscore?
bind
bindAll
partial
memoize
delay
defer
throttle
debounce
once
after
before
wrap
negate
compose



Thursday, 13 July 2017

Express JS Interview Questions and Answer for 1 Year Experienced

Express JS Interview Questions and Answer for 1 Year Experienced

Question: What Are Core Features Of Express Framework?
  1. Allows to set up middlewares to respond to HTTP Requests.
  2. Defines a routing.
  3. Dynamically render HTML Pages



Question: Why I Should Use Express Js?
It is light-weight server side web application framework which work on node.js platform.


Question: How to get The full Url In Express?
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host  + ':'+port + req.path;



Question: How to download a file?
app.get('/download', function(req, res){
  var file = __dirname + '/myfile/download.txt';
  res.download(file); 
});



Question: How To enable debugging In Express App?
In windows
set DEBUG=express:* & node index.js

In Linux
DEBUG=express:* node index.js


Question: How to render plain Html?
res.sendFile();
res.render();


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

app.get('/listing', function (req, res) {   
   res.send('This is listing API'); 
});

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



Question: How to receive get parameter in Express Js?
app.get('/listing', function (req, res) {   
    console.log(req.query);   //Receive get data
});



Question: How to receive post parameter in express Js?
app.post('/listing', function (req, res) {   
    console.log(req.body);   //Receive post data
});



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.


Question: How to send Ajax call in NodeJS?
Install the request
npm install request

request = require('request');
request( "http://exmaple.com:8081:/users/login/?username=testing@no-spam.ws&password=73278342", function(err, res, body) {                    
          console.log(res.console);          
      });



Question: How to get cookies in expressJs?
npm install cookie-parser
var express = require('express');
var app = express();

var cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/listing', function (req, res) {   
    console.log(req.cookies);    
});



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: List out some REPL commands in Node.js?
  1. Ctrl + c - For terminating the current command.
  2. Ctrl + c twice – For terminating REPL.
  3. Ctrl + d - For terminating REPL.
  4. Tab Keys - list of all the current commands.
  5. .break - exit from multiline expression.
  6. .save with filename - save REPL session to a file.



Question: How you can update NPM to new version in Node.js?
sudo npm install npm -g



Question: What do you mean by "Callback hell"?
"Callback hell" is referred to heavily nested callbacks which has become unreadable.


Question: What are "Streams" in Node.JS?
Streams are objects which will let you read the data from source and write data to destination as a continuous process.


Question: What you mean by chaining in Node.JS?
It's a mechanism in which output of one stream will be connected to another stream and thus creating a chain of multiple stream operations.


Question: What is the use of method – spawn()?
This method is used to launch a new process.
child_process.spawn(command[, args][, options])



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

    }
});