Skip to content

Creating and Publishing a Node.js Package to npm

This guide will help you create a Node.js package and publish it to npm.

Step 1: Set Up Your Development Environment

First, ensure you have Node.js and npm installed. You can verify the installations by running:

bash
node -v
npm -v

If you don't have Node.js and npm installed, follow the Installing Node.js and Package Managers on Ubuntu Server 22.04 guide.

Step 2: Create a New Node.js Project

Create a new directory for your project and navigate into it:

bash
mkdir my-node-package
cd my-node-package

Initialize a new Node.js project:

bash
npm init

Follow the prompts to set up your package.json file. You can accept the defaults or customize the fields as needed.

Step 3: Write Your Package Code

Create a new file named index.js and add your package code. For example, let's create a simple function that adds two numbers:

javascript
// filepath: /home/kelly/ws/guide/node/my-node-package/index.js
function add(a, b) {
    return a + b;
}

module.exports = add;

Step 4: Add Tests

It's a good practice to add tests for your package. Create a new directory named test and add a test file:

bash
mkdir test
touch test/test.js

In test/test.js, write a simple test for your add function:

javascript
// filepath: /home/kelly/ws/guide/node/my-node-package/test/test.js
const add = require('../index');
const assert = require('assert');

assert.strictEqual(add(2, 3), 5);
console.log('All tests passed!');

Run the test to ensure everything is working:

bash
node test/test.js

Step 5: Prepare for Publishing

Before publishing, you need to create an npm account if you don't have one. You can sign up at npmjs.com.

Log in to your npm account from the command line:

bash
npm login

Follow the prompts to enter your username, password, and email.

Step 6: Publish Your Package

To publish your package, run:

bash
npm publish

If the package name is already taken, you will need to choose a different name. You can update the name field in your package.json file and try publishing again.

Step 7: Use Your Published Package

You can now install and use your published package in any Node.js project. For example:

bash
npm install my-node-package

Then, require and use it in your code:

javascript
const add = require('my-node-package');
console.log(add(2, 3)); // Outputs: 5

Conclusion

You have successfully created and published a Node.js package to npm. You can now share your package with the world and use it in your projects.