exit_code.js (1957B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2019 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var proc = require( './process.js' ); 24 25 26 // VARIABLES // 27 28 var NODE_VERSION = proc.versions.node; 29 var TIMEOUT = 10; // ms 30 31 32 // MAIN // 33 34 /** 35 * Sets the process exit code. 36 * 37 * @private 38 * @param {Object} proc - process object 39 * @param {NonNegativeInteger} code - exit code 40 * @returns {void} 41 */ 42 function exitCode( proc, code ) { 43 var v; 44 45 // Handle old Node.js versions lacking `process.exitCode` support... 46 v = NODE_VERSION.split( '.' ); 47 v[ 0 ] = parseInt( v[ 0 ], 10 ); 48 v[ 1 ] = parseInt( v[ 1 ], 10 ); 49 50 // Case: >0.x.x 51 if ( v[ 0 ] > 0 ) { 52 proc.exitCode = code; 53 return; 54 } 55 // Case: >0.10.x 56 if ( v[ 1 ] > 10 ) { 57 proc.exitCode = code; 58 return; 59 } 60 // Case: <= 0.10.x 61 proc.exitCode = code; // NOTE: assigning this property should have no operational effect in older Node.js versions 62 63 // No choice but to forcefully exit during a subsequent turn of the event loop (note: the timeout duration is arbitrary; the main idea is to hopefully allow the event loop queue to drain before exiting the process, including the flushing of stdio streams which can be non-blocking/asynchronous)... 64 setTimeout( onTimeout, TIMEOUT ); 65 66 /** 67 * Callback invoked during a subsequent turn of the event loop. 68 * 69 * @private 70 */ 71 function onTimeout() { 72 proc.exit( code ); 73 } 74 } 75 76 77 // EXPORTS // 78 79 module.exports = exitCode;