JAVASCRIPT 31
Exit.js Guest on 3rd September 2020 05:53:08 PM
  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. };

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.