Hortinstein
Hortinstein

Reputation: 2697

How do I initialize two independent objects from same module in node.js/Javascript?

I am programming some mock server test cases for a program I am working on and have encountered an issue that i am unfamiliar with.

Here is the simple rest server

var restify = require('restify');
var server = restify.createServer();

var mock = {};
module.exports = mock;
var resp = '';
mock.init = function(name, port,callback) {
    resp = name;
    server.use(restify.bodyParser({
        mapParams: false
    }));

    server.get('/ping', function(req, res, next) {
        res.send(resp);
    });
    server.listen(port, function() {
        console.log('%s listening at %s', server.name, server.url);
        callback(undefined,server.url);
    });
};

and I try to initialize two servers with:

var should = require('should');

var mock1 = '';
var mock2 = '';

describe('mock riak load balancer', function() {
    it('should configure a mock riak node', function(done) {
        mock1 = require('./mock.js');
        mock1.init('mock1', 2222, function(e, r) {
            done();
        });
    });
    it('should configure a second mock riak node', function(done) {
        mock2 = require('./mock.js');
        mock2.init('mock2', 2223, function(e, r) {
            done();
        });
    });
});

Unfortunately I get a connection refused when I ping mock1, so it's being overwritten by the second call. Guessing this has something to do with the way Javascript handles scoping, but I am not sure.

I resorted to this: https://gist.github.com/hortinstein/5814537 but I think there has to be a better way

Upvotes: 0

Views: 560

Answers (1)

hereandnow78
hereandnow78

Reputation: 14434

it has to do with the way node.js loads modules. node.js caches required modules in your process, which means the mock2 is basically the same object as mock1.

more info:

Upvotes: 1

Related Questions