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