Recently I’ve been working with phantomjs in order to do some on-page control without wanting to use an actual browser (phantomjs is headless and requires no X server to be running).
One of the first things I wanted to do was created custom modules so I could organise my code clearly. I found a surprising lack of information on this topic so decided to quickly write up how I did it so it follows how the included modules work.
To use a custom module, you need to prefix the require with a path (./ works fine for the current directory) and exclude the .js extension:
var mymodule = require('./mymodule');
So in this case, alongside your primary JS file, you’d have a mymodule.js file.
Next, in mymodule.js, you’d write code something like this:
function MyCustomModule(){ ...your code here... } MyCustomModule.prototype.someFunction = function(){ ...your function code... }; exports.create = function(){ return new MyCustomModule(); };
This will allow you to return a new instance of your MyCustomModule class while using prototyping.
So going backing to the original require, to create a new instance you could do the following:
var customModule = require('./mymodule').create();
It’s really simple and obvious once you see it, there just was no where to see it!