[NodeJS] Some useful NPM packages
Modularity is in the philosophy of NodeJS, thus programmers are encouraged to use stable, robust, and battle-tested modules/packages instead of writing them on their own.
In this blog, I will walk you through few useful NodeJS packages available via the NPM repository.
There is no particular ordering for the list.
Express
Express is a web framework for NodeJS that allows developers to easily create server applications.
Express makes it easy to develop REST APIs with the model it provides.
Install it by running,
npm i express
An example of how it can be used in a NodeJS application is,
const express = require('express');
const app = express();// add middlewares for logging, auth, parsing, ...app.use((req, res, next) => {
console.log('Request receieved');
next();
});app.get('/', (req, res) => {
res.send('Hello world');
});app.listen(3000, () => {
console.log('App started');
});
Alternative package: Koa
Dotenv
Dotenv is a utility package that allows loading the environment variables defined in .env
into process.env
Install it by running,
npm i dotenv
An example for the usage of the package is,
require('dotenv').config();// Access any variable in .env file asconst PORT = process.env.PORT
Make sure that the above import statement is at the top level of the application.
Env-cmd
Env-cmd is an alternative to Dotenv. Without including import statement like in Dotenv
case, Env-cmd allows injecting values in .env
into process.env
Install package globally by running.
npm i -g env-cmd
Run your node application,
env-cmd node index.js
Multer
Multer is a package useful when handling file uploads in NodeJS applications. It is mainly used as a middleware in Express applications.
Install it by running,
npm i multer
An example for the usage of the package is,
const express = require('express');
const multer = require('multer');const app = express();// Single file upload
const upload = multer({ limits: { fileSize: MAX_FILE_SIZE_ALLOWED } }).single('usefile');app.post('/file', upload, (req, res) => {
// do something with req.file
res.send(`${req.file.originalname} uploaded`);
});app.listen(3000, () => {
console.log('App started');
});
There are many options available when working with Multer including file size limit, multiple file upload, in-memory, storage upload, … etc
Pino
Pino is a logger for NodeJS applications that has a low overhead.
Install it by running,
npm i pino
An example for the usage of the package is,
const express = require('express');
const pino = require('pino');const app = express();
const logger = pino();app.use((req, res, next) => {
logger.info('Request receieved');
next();
});app.get('/', (req, res) => {
res.send('Hello world');
});app.listen(3000, () => {
logger.info('App started');
});
Continuation-Local-Storage/Cls-hooked
Continuation-local-storage and its async version Cls-hooked are two packages that will allow developers to maintain something equivalent to a thread local-storage inside callback functions in NodeJS. This is very useful when maintaining a context in a NodeJS server application.
Install it by running,
npm i continuation-local-storage
or
npm i cls-hooked
An example for the usage of the continuation-local-storage package is,
const express = require('express');
const createNamespace = require('continuation-local-storage').createNamespace;const session = createNamespace('request-context');
const app = express();// request interceptorapp.use((req, res, next) => {const correlationId = req.headers.correlationid;
session.run(() => {
// set in the session
session.set('correlationId', correlationId);
console.log('Request receieved with correlation id', correlationId);next();
});
});app.get('/', (req, res) => {
// read from session
const correlationId = session.get('correlationId');
console.log('Serving the request with correlation id', correlationId);
res.send('Hello world');});app.listen(3000, () => {
console.log('App started');
});
What happens in the sample application implemented is, we are intercepting the request to the server by an Express middleware and capturing the correlationID
coming in the request, and setting it in the session context object. We can now use it anywhere in the application. (This is useful when logging)
Cron
Cron is a package that will allow us to execute a task on a schedule.
Install it by running,
npm i cron
An example for the usage of the package is,
const CronJob = require('cron').CronJob;const job = new CronJob('* * * * * *', () => {console.log('You will see this message every second');}, null, true);
UUID
UUID is a utility package that can be used to generate various UUID versions.
Install it by running,
npm i uuid
An example for the usage of the package is,
const uuid = require('uuid');const id = uuid.v4();
Axios
Axios is a useful library when your NodeJS application requires making HTTP requests.
Install it by running,
npm i axios
An example for the usage of the package is,
const axios = require('axios');axios(URL)
.then((res) => {
console.log(res.data);
})
.catch((error) => {
console.error(error);
})
Joi
Joi is an awesome library for schema validations. You can validate objects, request params and objects, … etc.
Install it by running,
npm i joi
An example for the usage of the package is,
const Joi = require('joi');emailValidator = Joi.string().email();const validateEmail = (email) => {const valid = emailValidator.validate(email);
return !valid.error;}validateEmail('not-an-email'); // false
validateEmail('test@gmail.com'); // true
The above code is a simple example of email validation, please read Joi documentation to get an idea of the power of the Joi.
Luxon
Luxon is a useful library when dealing with time and date calculation because the native support for that operation in JS is very limited.
Install it by running,
npm i luxon
An example for the usage of the package is,
const { DateTime } = require('luxon');const endOfDate =
DateTime
.fromJSDate(newDate())
.setZone('America/Chicago')
.endOf("day");const jsDate = endOfDate.toJSDate();console.log(jsDate);
In the above example, I’m getting the time of the end of today in America/Chicago
timeZone.
Camelcase
Camelcase is a package that converts any variable into the camel case form. This is useful when dealing with database column names which by the standard are in snake case form.
Install it by running,
npm i camelcase
An example for the usage of the package is,
const camelCase = require('camelcase');const dbResults = {
user_name: 'John Doe',
user_email: 'johndoe@gmail.com',
user_address: '123, city rd, NYC'
};const mappedResults = {};Object.keys(dbResults).forEach((key) => {const mappedKey = camelCase(key);
mappedResults[mappedKey] = dbResults[key];});console.log(mappedResults);//{
// userName: 'John Doe',
// userEmail: 'johndoe@gmail.com',
// userAddress: '123, city rd, NYC'
//}
Nodemon
Nodemon is a utility library that automatically restarts the project when a file changes. This is useful when testing a NodeJS server application like an Express which requires manual terminating and starting when files change.
Install it globally by running,
npm i -g nodemon
And run your node application
nodemon index.js
Lodash
Lodash can be called The utility library for JS applications. It has been implemented with performance in mind so that developers do not need to write utilities on their own.
Install it by running,
npm i lodash
An example for the usage of the package is,
const lodash = require('lodash');const users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 36 }
];// Sort by `user` in ascending order and by `age` in descending //order.const sorted = lodash
.orderBy(users, ['user', 'age'], ['asc', 'desc']);console.log(sorted);//[
// { user: 'barney', age: 36 },
// { user: 'barney', age: 34 },
// { user: 'fred', age: 48 },
// { user: 'fred', age: 40 }
//]
So there you have it.
I did not include packages like Webpack, Babel, ESLint, Jest which are also very useful when working with NodeJS.
Comment any other package you think I’ve missed.