2883e05935c38cd80024b492845faf612792c67a
[yaffs-website] / node_modules / exit / lib / exit.js
1 /*
2  * exit
3  * https://github.com/cowboy/node-exit
4  *
5  * Copyright (c) 2013 "Cowboy" Ben Alman
6  * Licensed under the MIT license.
7  */
8
9 'use strict';
10
11 module.exports = function exit(exitCode, streams) {
12   if (!streams) { streams = [process.stdout, process.stderr]; }
13   var drainCount = 0;
14   // Actually exit if all streams are drained.
15   function tryToExit() {
16     if (drainCount === streams.length) {
17       process.exit(exitCode);
18     }
19   }
20   streams.forEach(function(stream) {
21     // Count drained streams now, but monitor non-drained streams.
22     if (stream.bufferSize === 0) {
23       drainCount++;
24     } else {
25       stream.write('', 'utf-8', function() {
26         drainCount++;
27         tryToExit();
28       });
29     }
30     // Prevent further writing.
31     stream.write = function() {};
32   });
33   // If all streams were already drained, exit now.
34   tryToExit();
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);
40   });
41 };