Home Blog Work

Create your own npm module

Published on October 27, 2015

Hi there. Today I will show you how to create your own npm module and publish it to npmjs so that the world can use your work. If you don’t know what is npm it is an easy way to maintain the tried party libraries in your current project. Besides that, it also will do a lot of thing like run script etc. We will see all those things in some other post. In this post, we will only concentrate on how to create npm module and publish it to npmjs and also we will cover how to create command line tool using node.js. Before get start make sure you have nodejs or iojs installed in your system. If not please install them it’s pretty easy. Let’s create simple node program which should generate a random person name. (Inspired by PHP faker library


var fs = require('fs');

fs.readFile(__dirname +'/name.txt',function(err,data){
    console.log("There is an error");
    var names = data.toString().split('\n');
    var name = names[Math.floor(Math.random() * names.length)];

In this script, we are reading a file name.txt which will contain the one name per line and we are converting the file into JavaScript string array. We showing random name whenever user types command fake-name form command prompt. Let’s say this is your module you want to share on npm.js. Ok then. Open your command prompt and change directory to where you have this fake-name.js file and type

npm init

It will ask a couple of questions you have to answer them. Finally, it will ask you are you sure you want to create package.json then say yes. You should get a package.json file in your folder. Open that file and the following code to it.


So now, Your package.json file should look like this.

  "name": "fake-name",
  "version": "1.0.0",
  "description": "A Node.js library to create fake data for you.",
  "main": "fake-name.js",
  "scripts": {
    "test": "mocha test"
  "keywords": [
  "repository": {
    "type": "git",
    "url": "git+"
  "author": "Dimpu Aravind Buddha <> (//",
  "license": "MIT"

Once it did go back to your command prompt and type.

npm publish

Now you should see you package by going to Or by using npm search your-module-name That’s it enjoy.