No. When Node's module caching fails, that singleton pattern fails. I modified the example to run meaningfully on OSX:
var sg = require("./singleton.js");
var sg2 = require("./singleton.js");
sg.add(1, "test");
sg2.add(2, "test2");
console.log(sg.getSocketList(), sg2.getSocketList());
This gives the output the author anticipated:
{ '1': 'test', '2': 'test2' } { '1': 'test', '2': 'test2' }
But a small modification defeats caching. On OSX, do this:
var sg = require("./singleton.js");
var sg2 = require("./SINGLETON.js");
sg.add(1, "test");
sg2.add(2, "test2");
console.log(sg.getSocketList(), sg2.getSocketList());
Or, on Linux:
% ln singleton.js singleton2.js
Then change the sg2
require line to:
var sg2 = require("./singleton2.js");
And bam, the singleton is defeated:
{ '1': 'test' } { '2': 'test2' }
I don't know of an acceptable way to get around this. If you really feel the need to make something singleton-like and are okay with polluting the global namespace (and the many problems that can result), you can change the author's getInstance()
and exports
lines to:
singleton.getInstance = function(){
if(global.singleton_instance === undefined)
global.singleton_instance = new singleton();
return global.singleton_instance;
}
module.exports = singleton.getInstance();
That said, I've never run into a situation on a production system where I needed to do anything like this. I've also never felt the need to use the singleton pattern in Javascript.