Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is good practice when writing a node.js module

What is good practice when writing a node.js module

Problem

I can't really get a grip on what is considered to be good and bad Practice when writing a Module for in node.js. Some modules seem to use a lot of exports, while other use just one, etc.

Example:

var self;
var mymodule = function() {
    self = this;
    this.value1 = something;
    this.value2 = somethingElse;
};
module.exports.init = function() {
    return new mymodule();
};

mymodule.prototype.functionalityType1 = {
    someFunction: function(callback) {
        var a = self.value1;
        anotherfunction(a, callback);
    },
};
mymodule.prototype.functionalityType2 = {
    someFunction: function(callback) {
        var a = self.value2;
        anotherfunction(a, callback);
    },
};

var anotherfunction = function(v, callback) {
   // do stuff with v
   callback(result);
};

Each of the prototypes would contain more than one Function obviously.

Would something like this be considered good practice?

Problem courtesy of: JaHei

Solution

It really depends on what sort of module you are writing. Exporting multiple functions works well for utility modules which have multiple methods but little to no internal state to manage. Think something like the fs (file system) module. There are a number of file system methods, but they all pretty much stand alone and there is no shared state.

If you're building a stateful module with multiple methods which operate on state then you should probably just export a constructor and allow the client to create an instance of that object that they can manage. An example of this is the http module which allows you to create a server, and that server has methods which affect its internal state.

If you need to have more than one instance of an object from a module then you really don't have much choice but to export a function which returns an instance of the object.

It's not all that different from frameworks like .NET where you have file system (System.IO) classes which have static methods for standalone operations like verifying a directory exists, or reading the contents of a file and then they have instance classes for classes which maintain state.

Solution courtesy of: Timothy Strimple

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

What is good practice when writing a node.js module

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×