Categories
Node.js Tips

Node.js Tips — Router, Shutdown, File Name of Uploads, and etag

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Simple Ways to Gracefully Shutdown Express Apps

To make gracefully shut down Express apps easier, we can use the @moebius/http-graceful-shutdown module to make shutting down connections much easier.

To install it, we run:

npm i -S @moebius/http-graceful-shutdown

Then we can write:”

const express = require('express');
const GracefulShutdownManager = require('@moebius/http-graceful-shutdown').GracefulShutdownManager;

const app = express();

const server = app.listen(8080);

const shutdownManager = new GracefulShutdownManager(server);

process.on('SIGTERM', () => {
  shutdownManager.terminate(() => {
    console.log('Server is terminated');
  });
});

We just use the package’s GracefulShutdownManager constructor with our Express server.

Then we can watch for the SIGTERM signal and call the terminate method on it.

The callback in terminate will be called when termination is done.

‘Error: Most middleware (like json) is no longer bundled with Express and must be installed separately.’

With Express 4, we’ve to install most of the packages that used to be included individually.

We’ve to install packages like the body-parser and template engines.

For instance, to install body-parser, we run:

npm i body-parser

Then we can use it by writing:

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const ejs = require('ejs');

const app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

Store a File with File Extension with Multer

To store a file with the file extension with Multer, we can append the extension to the file name.

For instance, we can write:

const multer = require('multer');

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename(req, file, cb) {
    cb(null, `${Date.now()}.png`)
  }
})

const upload = multer({ storage });

We call the multer.diskStorage method with an object with a few methods.

The destination method specifies the folder to upload a file to.

In the filename method, we call the cb callback with the name of the file and the extension.

We can also get the extension from the MIME type in the filename method.

For instance, we can write:

const multer = require('multer');
import * as mime from 'mime-types';

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename(req, file, cb) {
    const ext = mime.extension(file.mimetype);
    cb(null, `${Date.now()}.${ext}`);
  }
})

const upload = multer({ storage });

We use the mime-types package to help us get the MIME type of the uploaded file, which we’ll use for the extension.

mime.extension lets us get the extension from the MIME type.

file is the file object. file.mimetype is the MIME-type.

Then we interpolate the extension into the file name string in the callback.

Set Default Path (Route Prefix) in Express

We can use the Express’s Router constructor to create a router object.

This is where we can add a route prefix to a route.

For instance, we can write:

const router = express.Router();
router.use('/posts', post);

app.use('/api/v1', router);

First, we create the router by calling express.Router() .

Then we call router.use to create a route with the path posts .

Then we call app.use to pass the router into it as the 2nd argument.

We have the /api/v1 prefix as specified as the first argument of app.use .

Also, we can chain them together by writing:

app.route('/post')
  .get((req, res) => {
    res.send('get post')
  })
  .post((req, res) => {
    res.send('add post')
  })
  .put((req, res) => {
    res.send('update post')
  });

We have the post path used by a GET, POST, and PUT route.

Disable etag Header in Express

We can disable etag header with Express by call app.set .

For instance, we can write:

app.set('etag', false);

to turn off the etag header.

We can also write:

app.disable('etag')

to do the same thing.

Conclusion

We can shut down an Express server gracefully with a package.

Also, we’ve to install most middleware that used to be included with Express ourselves.

We can get the extension from an uploaded file and tack it onto the uploaded file’s file name.

Express’s router can be chained.

The etag header can be disabled.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *