3 * https://github.com/cowboy/node-exit
5 * Copyright (c) 2013 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
11 module.exports = function exit(exitCode, streams) {
12 if (!streams) { streams = [process.stdout, process.stderr]; }
14 // Actually exit if all streams are drained.
15 function tryToExit() {
16 if (drainCount === streams.length) {
17 process.exit(exitCode);
20 streams.forEach(function(stream) {
21 // Count drained streams now, but monitor non-drained streams.
22 if (stream.bufferSize === 0) {
25 stream.write('', 'utf-8', function() {
30 // Prevent further writing.
31 stream.write = function() {};
33 // If all streams were already drained, exit now.
35 // In Windows, when run as a Node.js child process, a script utilizing
36 // this library might just exit with a 0 exit code, regardless. This code,
37 // despite the fact that it looks a bit crazy, appears to fix that.
38 process.on('exit', function() {
39 process.exit(exitCode);