Techumber
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 https://github.com/fzaninotto/Faker)

Facke-name.js

var fs = require('fs');

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

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.

"bin":{
  "faker":"fake-name.js"
},

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",
  "bin":{
    "faker":"fake-name.js"
  },
  "scripts": {
    "test": "mocha test"
  },
  "keywords": [
    "faker",
    "name",
    "random",
    "fake-data",
    "generator"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/dimpu/fake-name.git"
  },
  "author": "Dimpu Aravind Buddha <buddhaaravind@gmail.com> (//techumber.com)",
  "license": "MIT"
}

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

npm publish

Now you should see you package by going to https://www.npmjs.com/package/your-module-name-here Or by using npm search your-module-name That’s it enjoy.