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

Monday 4 March 2019

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: What is callback?
A callback function is called at the completion of a given task.


Question: What Are Arrow Functions?
Arrow functions – also called "fat arrow" functions, are a more concise syntax for writing function expressions.

Examples
const multiplyES6 = (x, y) => { return x * y };
const phraseSplitterEs6 = phrase => phrase.split(" ");
var docLogEs6 = () => { console.log(document); };



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


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS.


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.


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 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 Read Eval print Loop.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream as input.


Question: How to access the GET parameters after ? in Express?
req.query.name;



Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers.


Question: How we exporting a Module?
We use export for exporting the module.
exports.sayHelloInEnglish = function() {
    return "Hello, how are you?";
};



Question: What is meaning of tilde and caret?
the tilde(~) matches the most recent minor version.
the caret(^) matches the most recent major version.


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



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



Question: What is Async?
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});



Question: How to use expressJs in Node
var express = require('express');
var app = express();

//Add cookie to express
var cookieParser = require('cookie-parser');
app.use(cookieParser());

//Add session to express
var session = require('express-session');
app.use(session({
    secret: 'XEDDKJKXD',
    name: 'testname',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

//Add static path
app.use(express.static('public'))

//Add "Parse JSOn" to express
var bodyParser = require('body-parser')
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));

//Add middleware to express
app.use(function (req, res, next) {
  //console.log('Time2222:', Date.now())
 res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   
  next()
})


//Add https to expresJs
var https = require('https');
var privateKey  = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/georama.crt', 'utf8');
var caCertificate = fs.readFileSync('public/cert/chain.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);   


Question: How to start node on port?
httpsServer.listen(config['SERVERPORT'],function() {
    console.log('https listening on *:' + config['SERVERPORT']);
});



Question: How to connect socket with https?
var io = require('socket.io')(httpsServer);



Question: What is underscore module in nodeJS?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



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: Give simple example of ExpressJS?
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: What are different Middleware?
1) Application-level middleware
2) Router-level middleware
3) Error-handling middleware
4) Built-in middleware
5) Third-party middleware



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



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

    }
});