katrmr
katrmr

Reputation: 568

Node.js: using domain.dispose()

I'm writing a server in node.js and want to keep it running when a connection fails with an error. So, I'm trying to use the new domain module but can't find the right way to use domain.dispose().

First, node -v: v0.8.3

I supposed that domain.dispose() should be called on an error to clean up whatever the domain object has set up. But the result was not what I expected and I was unable to find any documentation or discussion on the proper usage.

This is the code I came up with to isolate the problem:

var domain = require('domain');
var EventEmitter = require('events').EventEmitter;

var i = 0;
function cycle() {
    process.nextTick(cycle);

    var emitter = new EventEmitter();
    emitter.i = ++i;
    emitter.on('test', function() {
        throw new Error('asdasd ' + emitter.i);
    });

    var dm = domain.create();
    dm.on('error', function(er) {
        console.error('Error', er);
        //dm.dispose();
    });
    dm.add(emitter);

    emitter.emit('test');
}

cycle();

It creates an EventEmitter, a separate domain for it, adds the emitter to the domain and triggers the emitter's error. Then it repeats.

All is well, the cycle goes on, errors are logged one after another:

[...]
Error { [Error: asdasd 1068]
  domain_thrown: true,
  domain: { members: [ [Object] ], _events: { error: [Function] } } }
Error { [Error: asdasd 1069]
  domain_thrown: true,
  domain: { members: [ [Object] ], _events: { error: [Function] } } }
[...]

Now, I add the domain.dispose() where I suppose it should be:

dm.on('error', function(er) {
    console.error('Error', er);
    dm.dispose();
});

This way, the cycle is repeated only two times:

Error { [Error: asdasd 1]
  domain_thrown: true,
  domain: { members: [ [Object] ], _events: { error: [Function] } } }
Error { [Error: asdasd 2]
  domain_thrown: true,
  domain: { members: [ [Object] ], _events: { error: [Function] } } }

No more output, the program just exits.

So, either I don't understand the purpose and semantics of domain.dispose(), or it does what it should not do. I'll probably dig into the source but in the meantime it would be nice to clarify the matter, if only for future generations. If you know how the function should be used to keep the application alive, please share. Thanks.

Upvotes: 1

Views: 1121

Answers (1)

bumpmann
bumpmann

Reputation: 685

By using v0.8.11 node will loop correctly with dm.dispose().

Upvotes: 3

Related Questions