Here Are 7 Useful Node Packages (Open Source and Free to Use!)

Take advantage of the vibrant JavaScript ecosystem and active community with these open source packages

JavaScript’s true power comes from the ocean of available open-source packages. The JavaScript ecosystem is booming with fabulous packages that we can use free of charge — but of course, don’t forget to sponsor the package creators and maintainers once in a while. The package authors are humans just like, and they also pay rent and buy groceries.

Without further ado, here are seven cool Node packages you can start using today.

Commander.js

Installation

Commander is the complete solution for node.js command-line interfaces, inspired by Ruby’s commander.

Installation

npm install commander

Declaring program variables

Commander exports a global object, which is convenient for quick programs.

const program = require('commander');program.version('0.0.1');

For larger programs that may use commander in multiple ways, including unit testing, it’s better to create a local Command object to use.

const commander = require('commander');
const program = new commander.Command();program.version('0.0.1');

Commands

You can specify (sub)commands for your top-level command using .command. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to .command, you specify the command name and any command arguments. The arguments may be <required> or [optional], and the last argument may also be variadic....

For example:

// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});// Command implemented using separate executable file (description is second parameter to `.command`)
// Returns top-level command for adding more commands.
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');

If you’re interested to learn more, head out to the official readme.

Passport

Install

Passport is Express-compatible authentication middleware for Node.js.

Passport’s sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport doesn’t mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer. The API is simple: You provide Passport a request to authenticate, and Passport provides hooks for controlling what occurs when authentication succeeds or fails.

Install

$ npm install passport

Usage strategies

Passport uses the concept of strategies to authenticate requests. Strategies can include verifying the username and password credentials delegated authentication using OAuth, or federated authentication using OpenID.

Before authenticating requests, the strategy (or strategies) used by an application must be configured.

passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));

There are 480+ strategies. Find the ones you want at passportjs.org.

Sessions

The Passport package will maintain persistent login sessions. In order for persistent sessions to work, the authenticated user must be serialized to the session and deserialized when subsequent requests are made.

Passport doesn’t impose any restrictions on how your user records are stored. Instead, you provide functions to Passport, which then implements the necessary serialization and deserialization logic. In a typical application, this will be as simple as serializing the user ID, and then finding the user by ID when deserializing.

passport.serializeUser(function(user, done) {
done(null, user.id);
});passport.deserializeUser(function(id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});

Head over to the official passport website to learn more about the project.

Chalk

Chalk includes the following

Chalk is a Node package for terminal styling.

Chalk includes the following

Install

$ npm install chalk

Usage

const chalk = require('chalk');console.log(chalk.blue('Hello world!'));

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

const chalk = require('chalk');
const log = console.log;// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

term-size

Install

The term-size NPM package will reliably get the terminal window size.

Process.stdout.columns doesn't exist when running non-interactively — for example, in a child process or when piped. This module even works when all the teletypewriter file descriptors are redirected!

Install

$ npm install term-size

Usage

const termSize = require('term-size');termSize();
//=> {columns: 143, rows: 24}

Term size has a short and sweet API

termSize()Returns an object with columns and rows properties.

Related

Note: The package is confirmed working on macOS, Linux, and Windows.

Nodemailer

Getting started

Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, and today it’s the solution most Node.js users turn to by default.

Nodemailer is licensed under MIT license. See license details in the License page. If you’re upgrading from Nodemailer v2 or older, then see the light migration guide here.

Getting started

npm install nodemailer

Nodemailer demo code

This is a complete example to send an email with a plain text and HTML body.

const nodemailer = require('nodemailer');// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount(); // create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass // generated ethereal password
}
}); // send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo@example.com>', // sender address
to: 'bar@example.com, baz@example.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
html: '<b>Hello world?</b>' // html body
}); console.log('Message sent: %s', info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com> // Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}main().catch(console.error);

Examples

  • Nodemailer AMQP is an example of using RabbitMQ to manage Nodemailer email messages. Source.

The output of the example script as shown by the Ethereal mail catching service:

Node MySQL

Installing

Node MySQL is a node.js driver for MySQL. It’s written in JavaScript, doesn’t require compiling, and is 100% MIT licensed.

Installing

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js. Node.js 0.6 or higher is required.

Installation is done using the npm install command:

$ npm install mysql

For information about the previous 0.9.x releases, visit the v0.9 branch.

Sometimes, it may also ask you to install the latest version from Github to check if a bugfix is working. In this case, please do this:

$ npm install mysqljs/mysql

Establishing connections

The recommended way to establish a connection to a database is the following:

var mysql      = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
} console.log('connected as id ' + connection.threadId);
});

Example Code

Here is an example of how to use the package.

var mysql      = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});connection.connect();connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});connection.end();

From this example, you can learn the following:

  • Every method you invoke on a connection is queued and executed in sequence.
  • Closing the connection is done using end(), which makes sure all remaining queries are executed before sending a quit packet to the MySQL server.

Head over to the official Github repository for an in-depth dive.

winston

Installation

winston is designed to be a simple and universal logging library with support for multiple means of transport. A transport is essentially a storage device for your logs.

Each winston logger can have multiple means of transport configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file.

winston aims to decouple parts of the logging process to make it more flexible and extensible. Attention is given to supporting flexibility in log formatting and levels, and also ensuring those APIs decoupled from the implementation of transport logging (i.e. how the logs are stored/indexed) to the API that they exposed to the programmer.

Installation

npm i winston

Usage

The recommended way to use winston is to create your own logger. The simplest way to do this is by using winston.createLogger:

const winston = require('winston');const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}

You may also log directly via the default logger exposed by require('winston'), but this is merely intended to be a conveniently shared logger to use throughout your application if you so choose.

Head over to the API documentation page for more information.

Conclusion

I hope you found at least one useful and new Node package to use in your existing or new project. However, if I missed your favorite package, share it below in the responses for everyone to see.

Note: Let’s not forget to sponsor and send love letters to the package authors. After all, they’re pretty much working for free and giving back to the world. Let’s reciprocate by giving back to the package creators.