DEV Community


Posted on

Writing your own npm module

What is npm?

npm stands for node package manager. npm makes it easy for developers to share code. Like every other package npm packages also have a manifesto file called package.json.

Installing node.js and npm

Best way of downloading node.js is to use the node installers from the node.js website. It is also good to have nvm(node version manager) to switch between different versions of node. Node.js comes with npm but it is best to update your npm. Run the following command to update your npm.

npm install npm@latest -g

Creating a package.json file

package.json has

  1. the list of dependencies your package depend on.
  2. specify the versions of the packages you’re using
  3. makes it easy to reuse your package to make a package.json file run
npm init

it will ask for some details like

name : name of your package
version : version of your package
description : what your package does
main : file that will have your main code (ideally should be index.js)
scripts : any scripts you want to run after , like tests or bower
author : who the package belongs to
licence : licence
you can also manually edit this file and add your dependencies. In the end your package.json will look something

  "name": "my_package",
  "description": "",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "repository": {
    "type": "git",
    "url": ""
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": ""
  "homepage": ""
  "dependencies": {
    "my_dep": "^1.0.0"

Writing your package

You write your script in the index.js you mentioned in the package.json. As mentioned you can use already published packages in your package.

var request = require('request');
exports.printMessage = function(){
  console.log("This is my npm package. Wohoo !");

Here I’m using request module to make an HTTP call.
To make your functions to be used , you need to export them. Here I export my printMessage function.
When people use your package they will npm install myNewPackage

var myPackage = require('myNewPackage');
myPackage.printMessage() // This is my npm package. Wohoo !

Publishing your npm package

To publish your package you must have an account on npm registry. Either make an account on the website or run

npm adduser

If you already have an account run

npm login

To check if you’re logged in run

npm whoami

It should prompt your username.
When you are done with all of this just hit

npm publish

and boom you’ve your npm package published.

Updating your npm package

When you’re done updating your package just change the version in your package.json and hit npm publish, your npm package will be updated.

Originally published on medium.

Top comments (0)