NodeJS: Creating your first global module

Software Versions
node.js 0.10.5
npm 1.2.18

Create the Module structure
Run the npm init command to create the base module structure.

mkdir test-module
cd test-module
mkdir bin && mkdir lib

echo ### Creating a test module > README.MD

Now that our module directory structure has been created, run npm init command to create the package.json file. Fill in the information as it pertains to your module.

npm init

Creating the library file
Let’s create an ~/lib/index.js file. This file will allow us to break down our library into smaller functions without revealing all the source to the module.

/**
* Says hello to a person.
*
* @param name Name of the person to greet.
*/
var sayHello = function(name) {
 return 'Hello, ' + name;
};

// Allows us to call this function from outside of the library file.
// Without this, the function would be private to this file.
exports.sayHello = sayHello;

Creating module file
Let’s create an ~/bin/test-module.js file. Please note that the first line (#!/usr/bin/env node) will allow npm to correctly generate an executable for this module.

#!/usr/bin/env node

var lib= require('../lib/index.js');
var greeting = lib.sayHello('Bret');

console.log(greeting);

An alternative way of including all libraries is to join the paths together.

var path = require('path');
var shifter = require(path.join('../lib'));

Installing a global Module: Don’t use npm link
The `npm link` command will allow global access to use the `require(‘test-module’) command in other modules. For a Windows machine, this is not the ideal solution as the npm link needs administrator privileges to use the symlink that is created. It is best to avoid this solution as it is not consistent across all environments in regards to security.

More information can be found at GitHub issue #1845.

Installing a global Module: use -g option
The -g options seems to be the best workaround to installing the module globally. This command will create an executable based on the “bin” configuration within the package.json file.

{
  "author": "Bret K. Ikehara",
  "license": "BSD",
  "name": "test-module",
  "version": "0.0.1",
  "description": "This is my first module.",
  "bin": {
    "test-module-exec": "bin/test-module.js"
  },
  "main" : "./lib/index.js",
  "preferGlobal": "true"
}

Install command:

npm -g install .

Running the module
According to our package.json file, the test-module-exec should be available to execute.

test-module-exec
Advertisements