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.


  • 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".



  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!


  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

Building and publishing an NPM Package

  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;

        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 = => 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 {
        . . .

        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) {

    $ node example.js
    # fyi


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.


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

Building and publishing an NPM Package

    $ 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 .

Building and publishing an NPM Package

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

    $ npm link acronym 
    # link-install the acronym package

Now the node_modules directory should look like this:

Building and publishing an NPM Package

    ├─ 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.



  • 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.

Building and publishing an NPM Package

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:

Building and publishing an NPM Package

    ├─ 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.

Building and publishing an NPM Package

    $ npm whoami
    # akinjide

Use npm publish to publish the package. You should see the package information when you visit []( Replace `` with the package name.

Building and publishing an NPM Package

    $ npm publish
    # + [email protected]


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

    $ npm unpublish
    # - [email protected]


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.


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.

node-js npm

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.

Node.js Performance: Node.js vs. Io.js

You may already be aware that Raygun uses Node.JS for our API nodes that receive your precious crash reporting data (we also do node.js crash reporting if you’re interested). We’ve peaked in the past at more than 110,000 requests per second coming...

Node.js Live | Node.js Docker Tutorial | Dockerizing Node.js App|Node.js Training|Edureka

🔥 Node.js Certification Training: This Edureka video on 'Node.js Docker Tutorial' will help you in learn...