exit.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. 'use strict';
  9. module.exports = function exit(exitCode, streams) {
  10. if (!streams) { streams = [process.stdout, process.stderr]; }
  11. var drainCount = 0;
  12. // Actually exit if all streams are drained.
  13. function tryToExit() {
  14. if (drainCount === streams.length) {
  15. process.exit(exitCode);
  16. }
  17. }
  18. streams.forEach(function(stream) {
  19. // Count drained streams now, but monitor non-drained streams.
  20. if (stream.bufferSize === 0) {
  21. drainCount++;
  22. } else {
  23. stream.write('', 'utf-8', function() {
  24. drainCount++;
  25. tryToExit();
  26. });
  27. }
  28. // Prevent further writing.
  29. stream.write = function() {};
  30. });
  31. // If all streams were already drained, exit now.
  32. tryToExit();
  33. // In Windows, when run as a Node.js child process, a script utilizing
  34. // this library might just exit with a 0 exit code, regardless. This code,
  35. // despite the fact that it looks a bit crazy, appears to fix that.
  36. process.on('exit', function() {
  37. process.exit(exitCode);
  38. });
  39. };