1) What is middleware functions in Express.js?

Middleware is a functions that performs some preparatory or commonly used action before passing request to main handler. For example you need to check user session on every request, so you write middleware functions, that check it, so you don't duplicate this check in all controllers.

import * as express from 'express';const app = express();app.use(function(req,res,next) {
  const token=req.headers['token'] || req.cookies.token;
  let result=tokenService.verifyToken(token);
  if(result.error){
    return NotAuthorized(req,res);
  }
  req.user=result;
  return next(null,req,res);});

2) How to make a redirect to specific URL?

To redirect to specific URL use response method redirect([status,] path). It accepts one two parameters: URL,redirect status code or just URL.

res.redirect(301, 'https://domain.com');res.redirect('https://domain.com');

3) How to get query params?

You can get query params in req.params object.

router.get('/api/user/:userId', async function (req, res, next) {
  const userId=req.params.userId;});

4) What is template engines and how to use them?

A template engine allows you to use static template files in your application to render dynamic HTML responses. To use template engine use app.set() method.

app.set('view engine', 'hbs')

5) How to run Express.js server in production mode?

To run Express server in production mode, you should set NODE_ENV variable to 'production'. By default server works in development mode.

$ NODE_ENV=production node bin/www

6) How to automatically redirect HTTP traffic to HTTPS?

There is couple of way to do it. First is to utilize res.redirect method, second to use Nginx or HAProxy as reverse proxy

const http = express.createServer();http.get('*', function(req, res) {  
    res.redirect('https://' + req.headers.host + req.url); 
});
http.listen(80);

For Ngnix:

location / {
    proxy_pass http://localhost:8080;}

7) How to run Express.js app in cluster mode?

It's well know fact, that Node.js is single threaded, so your can't fully utilize multi-core system capacities running in single mode. To run multiple instance of Express.js built in 'cluster' module should be used.
const cluster = require('cluster');if (cluster.isMaster) {
  const cpuCount = require('os').cpus().length;
  for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }} else {
    const express = require('express');
    const app = express();
    app.get('/', function (req, res) {
        res.end('Rendered in cluster mode.!');
    });
    app.listen(8080);}

8) How to handle file upload?

Express doesn't provide file upload api out the box, but you can use one of various middlewares, which are availble at NPM. In following example we use a 'multer' package.

import * as express from 'express'
const router = express.Router();
import * as multer from "multer"
const fs = require('fs');
const appRoot = require('app-root-path').path;
const upload = multer({ dest: appRoot+'/uploads' });
router.post('/api/v1/upload/image',upload.single('image'), function(req:any, res, next) {
  const sanitize = require("sanitize-filename");
  if(!req.file){
    return res.json({error:'No image provided'});
  }
  const newFileName=`${req.file.path}_${sanitize(req.file.originalname)}`;
  fs.rename(req.file.path, newFileName, function(err) {
    if ( err ) console.log('ERROR: ' + err);
  });
  res.send({status:"OK"});});
export {router};

9) ExpressJS how to structure an application?

There is no official recommendation about how to structure Express.js application, so creating architecture rests on the shoulders of developer. There is some recommendation about directory structure.

├── app.js   // file where express server started
├── config   // Configuration files
├── models   // Data models for Sequlize or Mongoose
├── public   // Directory for static assets
├── routes   // The routes in you application, with controller functions
├── services // Any other service utils your application using
└── views    // Template engine views (HBS,JADE,EJS)

10) How to restart Node.js application when uncaught exception happens?

When application works in production, uptime should be as big as possible, so there is a need of service that will restart server after critical error. There is several command line utils, which can do this: forever,pm2,nodedemon. The main difference is that you start application through this util,you don't run it with 'node' command directly. Also this packages save logs of application, provides information about memory usage and current uptime.

pm2 start app.js

11) Does Express.js supports basic auth?

No, express doesn't support it out of the box, but there is library express-basic-auth, which helps to add this feature to app.

12) What res.end() function do?

res.end function ends response process. It can be used to quickly send response with no data or when you to signal that you write last chunk of buffered data.

app.use(function(req, res) {res.status(404).end();})

13) How to send JSON response?

The easiest way to send JSON response is to use res.json(data) method. It will automatically add correct content-type to response headers and transforms passed object to JSON. However you could it on your own using res.send() and setting headers.

router.get('/api/image-dimensions',upload.single('image'), function(req, res, next) {const json=getImageDimension();res.header('Content-Type', 'application/json');res.send( json );        
})

14) What res.type(type) function do?

Function res.type(type) change the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type.

res.type('html');// => 'text/html'

15) Describe main differences between and Express.js and Sails.js?

  • Sails.js is more powerful, it have own ORM, can auto-generate REST API's, built'n WebSocket support, defined application structure. Express.js can't do nothing similar without additional libraries and middlewares.
  • Express.js is more flexible than Sails.js, you can build your app like a constructor. Sails.js severely limits developer ability to change application structure.
  • Express.js is easier to learn, which is great for beginner programmers.
  • Sails.js has powerful CLI utility

16) What is 'express-generator'?

Express generator is util to generate express.js apps. Before project generation you can configure template engine,stylesheet engine, .gitignore file.

$ npm install -g express-generator
$ express --view=hbs /tmp/foo && cd /tmp/foo

17) What is router?

A router object is an isolated instance of middleware and routes. Router is a basic class to implement REST api and Website pages. router.METHOD(path, [callback, ...] callback) method is used to add route.

18) Could route handler function be async?

Yes, it's is possible to utilize async/await in express.js controller functions.

19) How to send file using Node.js streams ?

Node.js streams allows read and write buffered data. For example it's very useful when file doesn't feet in ram, so you don't reed full file, just process it in chunks.

router.get('/api/v1/image-proxy/:name', function(req, res) {
  return require('request').get('some url'+req.params.name).pipe(res);
})

20) Why is important to distinguish operational and programmer errors ?

Operational errors are not bugs, but problems with the system, like down database or full hard drive, programmer error is a bug which leads to incorrect application behaviour. It's good practise to be ready to any operational error and handle gracefully without crashing.