Abnormal Exit

40 views
Skip to first unread message

Alan Gutierrez

unread,
Jul 15, 2012, 2:18:53 PM7/15/12
to nod...@googlegroups.com
I'm writing command line utilities in Node.js. Here's a snippet that is
a source of some concern for me.

try {
options = require('arguable')(__filename);
} catch (error) {
console.error('error: ' + e.message);
console.error(e.usage);
process.exit(1);
}

frobinate(options.severity);

Essentially, I'm calling an options parser and finding errors that
prevent me form continuing. I want to exit with a non-zero exit code.

However, if I exit abruptly, I find that the console is not always
flushed. Sometimes on Windows. Sometimes when piping stderr.

I'm wondering when I can count on a flush of stderr before exit, when I
can't, and what you feel is the right way to exit from a command line
program, if you have any thoughts on the matter.

Currently, I'm creating a main function, surrounding that in a try/catch
block, and throwing special exceptions to indicate that the error does
not involve a stack trace.

--
Alan Gutierrez - http://github.com/bigeasy - http://twitter.com/bigeasy

Dominic Tarr

unread,
Jul 15, 2012, 9:25:50 PM7/15/12
to nod...@googlegroups.com
you can throw anything in js, even an empty string.
(a good way to break a test framework)

would this work?

stderr.on('drain', function () {
process.exit(1)
})

console.error('fail')
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+un...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en

Alan Gutierrez

unread,
Jul 15, 2012, 11:56:07 PM7/15/12
to nod...@googlegroups.com
Wouldn't that abruptly exit the program the first time stderr drains? I
imagine that it drains multiple times during the life of the program, if
I write warnings while running.

Currently, I'm doing...

try {
main();
} catch (e) {
if (e.code != null && !isNaN(e.code))
process.on('exit', function () { process.exit(e.code) });
else
throw e;
}

But, I'm trying to imagine situations where catching that error in that
way will cause the program to keep on going, instead of petering out.

Dominic Tarr

unread,
Jul 16, 2012, 1:27:13 AM7/16/12
to nod...@googlegroups.com
oh, you would have to assign the 'drain' listener after you've decided to exit.
Reply all
Reply to author
Forward
0 new messages