Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is good practice when writing a node.js module

Tags:

node.js

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?

like image 362
JaHei Avatar asked Mar 27 '12 10:03

JaHei


1 Answers

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.

like image 57
Timothy Strimple Avatar answered Sep 27 '22 21:09

Timothy Strimple