Creating Custom Modules in Node.js

If you’ve been using Node.js, you’ve probably been using modules for some time. A module is basically a javascript file that exposes internally scoped functions using the exports variable. In this tutorial, I’ll show how to create a simple string splitting module to give you a basic understanding.

Getting Started
Lets start off by creating our directory.

mkdir StringSplitterModule
cd StringSplitterModule

Creating package.json
In the StringSplitterModule directory we just created, run npm init to automatically create your package.json file. You’ll be asked a series of questions about your app.

npm init

Your package.json should look something like this:

{
  "name": "StringSplitterModule",
  "version": "0.0.0",
  "description": "String Splitter Node Module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "Jason Everett",
  "license": "BSD"
}

StringSplitter.js
Now lets create our module that we’ll call StringSplitter.js.

exports.SplitMe = function(stringToSplit, delimiter)
{
	return stringToSplit.split(delimiter);
};

As you can see this a super simple module that splits a string and returns an array using javascript’s built-in split function. Using the exports variable we’ve exposed the SplitMe function.

index.js
Next we’ll create our index file that will use our StringSplitter module.

var myCustomModule = require('./StringSplitter.js');

console.log(myCustomModule.SplitMe('Texas, Florida, Seattle', ','))

We use require('./StringSplitter.js') to invoke our module. Using require, Node.js will evaluate the file and load the functions defined in the exports object.

Now all you need to do is run your app.

node index.js

You should see the following results in your console application:
[ 'Texas', ' Florida', ' Seattle' ]

Creating a module is really not complicated. Publishing your custom modules in npm registry is also not that complicated but I’ll save that for a future tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please Do the Math      
 

*