ClockEndGooner ClockEndGooner - 2 months ago 11
Node.js Question

How To Export A Class Implemented In A Namespace In node.js

I've created a class inside a namespace in node.js 4.5.0, whose implementation is as follows;

//
// Contents of MyList.js
//
"use strict";

var MyCollections {};

(function() {
this.List = function () {
//
// Simple List implementation ...
//
}
}).apply(MyCollections);


In my script where I'd like to instantiate MyCollections.List class, I've coded the following;

//
// Contents of CheckList.js
//
"using strict";

var collections = require('../MyList');

var list = new collections.List();


When running the above script through node, I receive the following;

PS C:\work\node.js\MyCollections\List> node .\CheckList.js
Number of Items in List: 2
C:\work\node.js\MyCollections\List\CheckList.js:6
var list = new collections.List();
^
TypeError: collections.List is not a function
at Object.<anonymous> (C:\work\node.js\MyCollections\List\CheckList.js:6:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3


Given the implementation of the List class in MyList.js above, what should I change to make the List class exportable so I can reuse it in more than one script?

My apologies if this is has been previously posted and answered, as I may have used the wrong terms in describing what I'm trying to do. My intent is to declare a namespace and expose the function prototypes that implement a collection class, in this case, a simple list, while maintaining some degree
of encapsulation. I believe that my List class implementation is correct, as when I try to instantiate and populate a List of integers in the same script, MyList.js, the functions in the list work as expected. For example;

//
// Statements after (function() { //... }).apply(MyCollections);
//

var list = new MyCollections.List();

list.append(1);
list.append(2);
list.append(3);
list.append(4);

console.log("Number of Items in List: " + list.count());

while (list.hasNext()) {
var trace =
'Item ' + (list.position() + 1) + ' of ' + list.count() + ' = ' +
list.getItem();

console.log(trace);

list.next();
}

//
// Output:
//
Number of Items in List: 4
Item 1 of 4 = 1
Item 2 of 4 = 2
Item 3 of 4 = 3
Item 4 of 4 = 4


Thank you in advance for your time, help and patience.

Answer

You need to export the MyCollections. Add the following to your MyList.js:

module.exports = MyCollections;

So the updated file has the following content:

//
// Contents of MyList.js
//
"use strict";

var MyCollections = {};

(function() {    
    this.List = function () {
    //
    // Simple List implementation ...
    //
    }
}).apply(MyCollections);

module.exports = MyCollections;