Step by step: Building and publishing an NPM Package

Step by step: Building and publishing an NPM Package

In this article, we'll look at creating an npm package that can be installed as a dependency and publish to npm.

Every Node.js developer knows that when creating a new Node project, one of the very first things you'll do is type npm init and answer couple questions, and then install dependencies and devDependencies.

Table of Contents

  • What is a package and module?
  • Prerequisites
  • Setup
  • Getting started
  • Test
  • Publish
  • Conclusion
What is a package and module?

npm has specific definitions of packages and modules, which are easy to mix up. I'll like to discuss these definitions and explain certain default files.

Note

  • A package is a folder containing a program described by a package.json file that defines the package.
  • A module is a folder with a package.json file, which contains a main field, that enables loading the module with require() in a Node program.
  • The node_modules folder is the place Node.js looks for modules.

Generally, most npm packages are modules. However, there's no requirement that an npm package should be a module. There are CLI packages, that contain only executable command-line interface(CLI) and don't provide a main field to be loaded with require(), these type of package is not a module.

In the context of a Node program, the module is loaded from a file. For example, in the following program:

    var acronym = require('acronym');

we can say that "variable acronym refers to the acronym module".

Prerequisites

Note

  1. Important words are highlighted.
  2. Bold words emphasis a point.
  3. Previous / Next code appears like this . . . .

This project requires a fair understanding of Javascript Promises and Callbacks and Node.js v6.11.0 LTS or higher to support some ECMAScript 2015 features. You can follow this tutorial or view the full code for this tutorial on Github.

Now that you have completed the prerequisites, let's start!

Setup
  1. Create an empty directory and initialize it as a npm package using npm init or npm init --yes, if you're feeling lazy. It will ask you to create your package.json file.

$ mkdir acronym && cd acronym $ npm init --yes


  1. Navigate to your directory, a package.json file should exist like this :
    {
          "name": "acronym",
          "version": "1.0.0",
          "description": "",
          "main": "index.js",
          "scripts": {
              "test": "echo \"Error: no test specified\" && exit 1"
          },
          "author": "",
          "license": "ISC"
    }
  1. By default, a main field will get created. The main field is a module ID, the entry point (main script) to your program. That is, if a user installs this package, and then does require("acronym"), the main module exports object will be returned.
  2. Edit the package.json file to look like this, if you want to add information for the author field, you can use the format Your Name (email is optional):
    {
          "name": "acronym",
          "version": "1.0.0",
          "description": "Transform sentences to acronyms.",
          "main": "index.js",
          "author": "Akinjide Bankole " // optional
    }
  1. Let's start creating our script file and open with Sublime Text (or Atom, VIM, WebStorm) :
    $ touch index.js
    $ open . -a 'Sublime Text'
Getting started
    "use strict";

    module.exports = function acronym(sentence, callback) {

    }

module.exports encapsulates and allows the acronym function to be with other code. The acronym function takes two parameter, a string data type e.g. "for your information" and a callback function.

    . . .

    return new Promise((resolve, reject) => {

    });

    . . .

We define and return an instance of the Promise class. A Promise is an object which can be returned synchronously from an asynchronous function, it may be in one of 3 possible states: fulfilled, rejected, or pending, and produces a single value some time in the future.

  • Fulfilled will be called when resolve() is called.
  • Rejected will be called when reject() is called.
  • Pending is either not yet fulfilled or rejected.
    . . .

    if (sentence.length === 0) {
        reject('String, Please! e.g. "for your information"');
        return callback('String, Please! e.g. "for your information"');
    }

    . . .

The if statement checks for the length of the sentence parameter, if the condition is true, we reject with an error message (String, Please! e.g. "for your information"). The return keyword before the callback, immediately breaks out of the function call, returning the callback function with an error message.

    . . .

    else if (typeof sentence === 'function') {
        callback = sentence;

        reject('¯\\_(ツ)_/¯');
        return callback('¯\\_(ツ)_/¯');
    }

    . . .

The else if statement checks if the user passes in a function as the first parameter instead of a string, if the condition is true, we assign the function to callback and reject with an error message (¯\\_(ツ)_/¯).

    . . .

    else {
        const words = sentence.split(' ');
        const acronym = words.map((word) => word[0]);

        . . .
    }

The else statement will be the default if none of the conditions above was satified. The first line, we .split the sentence into an array ['for', 'your', 'information']. The second line, we .map and return an array, with the first character of each word ['f', 'y', 'i'] and assign to variable acronym.

    . . .

    else {
        . . .

        resolve(acronym.join(''));
        return callback(null, acronym.join(''));
    }

We .join and resolve the acronym array, and return the callback function with null as error and the joined acronym array.

So far we have created the package.json, index.js file. Let's create a script file, open with Sublime Text (or Atom, VIM, WebStorm) and test our index.js:

    $ touch example.js
    $ open example.js -a 'Sublime Text'
    const acronym = require('./'); // require the `index.js` file from the same directory.

    acronym('for your information', (err, resp) => {
        if (err) {
            console.log(err);
        }

        console.log(resp);
    });
    $ node example.js
    # fyi
Test

Working on a package and testing iteratively without having to continually rebuild or publish to npm registry has been a major concern to package authors. npm link is an handy way of linking and testing packages locally before publishing.

npm link basically links a package folder to the global node_modules directory. Package linking is a two-step process. First, you'd npm link the pacakge folder, creating a symlink in the global node_modules.

Note

  • Replace `` with the folder where the acronym project exists previously.
  • Replace `` with an exisiting node project or create a new one for testing.

    $ cd ~//acronym
    # go to the package directory

    $ npm link
    # create a global symlink

Next, in , `npm link acronym` creates a link from the globally installed `acronym` to the **node_modules** directory of the .

    $ cd ~// 
    # go to some other package directory.

    $ npm link acronym 
    # link-install the acronym package

Now the node_modules directory should look like this:

    ├─ node_modules   
    │   ├─ acronym -> ../../.nvm/versions/node/v4.6.1/lib/node_modules/acronym      
    ├─ package.json

With npm link, requiring the local project becomes easy and we publish to npm when we are entirely ready.

We've tested the module locally, now we publish.

Publish

Note

  • Make sure that everything in the directory is vetted, or ignored using .gitignore.
  • Make sure that there isn't already a package with the same name, if there's a an exisiting project you'll get an error has below.

As I mentioned, we'll be publishing this package to the npm registry so that it can be installed by name. Before we publish make sure your acronym directory looks like this:

    ├─ acronym   
    │   ├─ index.js
    │   ├─ example.js
    │   ├─ package.json    

As with every registry, you must have a user on npm registry. If you don't have one, create it with npm adduser or using npm site. If you've created using npm site, use npm login to store the credentials.

Use npm whoami to ensure that the credentials are stored.

    $ npm whoami
    # akinjide

Use npm publish to publish the package. You should see the package information when you visit [https://npmjs.com/package/](https://npmjs.com/package/). Replace `` with the package name.

    $ npm publish
    # + [email protected]

Unpublish

If you'd like to remove your package from the npm registry, use npm unpublish to publish the package.

    $ npm unpublish
    # - [email protected]

Updating

When you make changes to your code and want to update the package you'll need to update the version of the package. Use npm version , where `` is a sematic versioning release type patch, minor or major. After updating the version number, you'll need to publish the package again, use npm publish.

Conclusion

Congrats! You now know how to build a node module, make it a package and publish to the npm registry. Feel free to use the code above and contributions are welcome.

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

How to Install Node.js with npm on Debian 10

How to Install Node.js with npm on Debian 10

Install Node.js with npm on Debian 10 In this tutorial, we are going to learn how to install Node.js with npm on Debian 10

Table of Contents

Install Node.js with npm on Debian 10

In this tutorial, we are going to learn how to install Node.js with npm on Debian 10. Node.js is the opensource JavaScript Run-time environment for server-side execution of JavaScript code. Node.js built on Chrome’s V8 JavaScript engine so it can be used to build different types of server-side applications.

Where npm stands for Node Package Manager which is the default package manager for Node.js. npm is the world’s largest software registry for Node.js packages with thousands of packages available.

In this tutorial we will install Node.js in following two ways:

  1. Install Node.js and npm using Debian repository
  2. Install Node.js and npm using nvm
  3. Install Node.js from the NodeSource repository.

1. Install Node.js and npm using Debian repository

First, Update Debian apt package manager index by running the following command.

sudo apt update

Install Node.js from Debian global repository by typing

sudo apt install node

Confirm the installation of Node.js by typing

node --version

Install npm by running following command

sudo apt install npm

Confirm the installation of npm by typing

npm --version

2. Install Node.js and npm using nvm

NVM stands for Node Version Manager which is used to manage multiple Node.js versions. If you want to install or uninstall different versions of Node.js then NVM is there for you.

First, we will install NVM (Node Package Manager) on your system. So download the NVM installation script running the following command.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Check nvm version and confirm installation typing

node --version

Now install Node.js by using the following command.

nvm install node

Verify Node.js installation by typing

node --version

The output should be:

Output

v10.14.0

You can install multiple versions of Node.js. To do so type the following:

nvm install 8.14
nvm install --lts
nvm install 11.3

To list all the versions installed run following command.

nvm ls

You can change the current default version of Node.js by using the following command.

nvm use 8.14

To uninstall a Node.js version type following command

nvm uninstall 11.14

Install Node.js from NodeSource Repository

NodeSource company provides enterprise-grade node support also maintains the repository containing the latest version of Node.js.

To enable the NodeSource repository on your system run following command.

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -

NOTE: The latest LTS version of Node.js is 10.x if you want to install 8.x version then just replace setup_10.x with setup_8.x

Now install Node.js and npm package typing.

sudo apt install nodejs

Verify installation of Node.js and npm running following command

node --version
npm --version

Install Development Tools

Now install some packages needed for development by running following command

sudo apt install gcc g++ make

Uninstall Node.js and npm

Uninstall Node.js use following command

sudo apt remove nodejs npm
sudo apt autoremove

To uninstall node.js version using nvm type following command

nvm uninstall 10.14

Conclusion

You have successfully learned how to install Node.js with npm on Debian 10. If you have any queries don’t forget to comment below.

Hashing Passwords with Node.js and NPM Bcrypt Library

Hashing Passwords with Node.js and NPM Bcrypt Library

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.js

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.

To create a secure application, it is always considered a safe practice not to store a user’s password in the database in plain text format. If not in plain text format, then what else we can do?

Here is the solution, generate a hash (complex string and numbers) and store that hash in the database. You can decipher your hashed password later by using the comparing method.

Let’s assume if there was a breach in your database, and all your stored passwords were leaked. Then, you are at significant risk, and password hashing is the best one-way encryption technique to secure the passwords.

In this method, you do not store users’ passwords in the database in its original form. Instead, a password is stored in a complex combination of text and unique characters; this is known as a password hash method.

A hacker can not easily decipher an adequately hashed password. Hackers will get frustrated because it will take lots of time and effort to decrypt the password.

In this tutorial, we will learn how to install and correctly hash a password in node.js.

We will take the help of the NPM BcryptJs package, and it is a widely used encryption module available nowadays via NPM.

Before we begin, you must have Node.js configured in your machine. If not, then you can check out how to install Node in your system tutorial.

Install bcryptjs Npm Module

To get started i assume you already have a Node.js project setup along with Express, and MongoDB.

Run one of the command based on your package manage.

# npm
npm install bcryptjs --save

# yarn
yarn add bcryptjs

Now, once bcryptjs successfully installed. We are ready to go ahead!

Hash A Password with Bcrytp Js

To get started with hashing the password we need node server configuration. In the app.js file, we imported express, bodyParser, mongoose and bcrytpjs module. We defined the MongoDB database connection, user schema and two REST APIs for registering and signing in the user.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');

// Express APIs
const api = require('./routes/auth.routes');

// MongoDB conection
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/nodedb", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Database connected')
},
    error => {
        console.log("Database can't be connected: " + error)
    }
)

// Express settings
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors());

app.use('/api', api)

// Define PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
    console.log('Connected to port ' + port)
})

// Express error handling
app.use((req, res, next) => {
    setImmediate(() => {
        next(new Error('Something went wrong'));
    });
});

app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

Hashing a password is very simple, the first argument in the bcrypt.hashSync() method is the password which we are getting from req.body middleware. The second argument is the number of rounds which we set to 10 to generate a salt.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-up
router.post("/signup", (req, res, next) => {
    bcrypt.hash(req.body.password, 10).then((hash) => {
        const user = new userSchema({
            name: req.body.name,
            email: req.body.email,
            password: hash
        });
        user.save().then((response) => {
            res.status(201).json({
                message: "User successfully created!",
                result: response
            });
        }).catch(error => {
            res.status(500).json({
                error: error
            });
        });
    });
});

So we are hashing the password when the user makes the signup call after that we are creating a user instance and saving the user data along with the password in the MongoDB database.

Verify or Compare The Password with Bcrypt

When the user logs in the app, API will check the if the email exists in the database with the help of userSchema.findOne() method. Then, we will validate the stored password with the help of bcrypt.compareSync() method. It takes two passwords as an argument stored password and user-entered password.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-in
router.post("/signin", (req, res, next) => {
    let getUser;
    userSchema.findOne({
        email: req.body.email
    }).then(user => {
        if (!user) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
        return bcrypt.compare(req.body.password, user.password);
    }).then(response => {
        if (!response) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
    }).catch(err => {
        return res.status(401).json({
            message: "Authentication failed"
        });
    });
});
Conclusion

We have seen how to store the password in the database securely by making the REST API call with Node/Express.