Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wait for streams to drain before exiting #26

Merged
merged 1 commit into from
Oct 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ const ECHO_RED_FORMAT = "\x1b[31m%s\x1b[0m";
const ECHO_BLUE_FORMAT = "\x1b[34m%s\x1b[0m";

global.dirname = path.dirname;
global.exit = process.exit;

/**
* Echos error message to stdout and then exits with the specified exit code (defaults to 1)
* @param error The error message string or Error object to print
* @param exitCode
*/
const _error = (error: string | Error, exitCode: number = 1) => {
console.error(ECHO_RED_FORMAT, error); // Will print to stderr
exit(exitCode);
_exit(exitCode);
};
global.error = _error;

Expand All @@ -57,7 +57,7 @@ const _printUsageAndExit = (exitCode = 1, additionalMessage?: string): void => {
}
}

exit(exitCode);
_exit(exitCode);
};

const _usage = (message: string, printAndExitIfHelpArgumentSpecified = true) => {
Expand Down Expand Up @@ -200,6 +200,32 @@ const _stdin = () => {
};
global.stdin = _stdin;

const _exit = (exitCode: number = 0) => {
// Ensure all streams are drained before exiting (code pulled from https://github.com/cowboy/node-exit)
let streams = [process.stdout, process.stderr];
let drainCount = 0;
function tryToExit() {
if (drainCount === streams.length) {
process.exit(exitCode);
}
}
streams.forEach(function (stream) {
// Count drained streams now, but monitor non-drained streams.
if (stream.writableLength === 0) {
drainCount++;
} else {
stream.write("", "utf-8", function () {
drainCount++;
tryToExit();
});
}
// Prevent further writing to stream
stream.write = <any>function () {};
});
tryToExit();
};
global.exit = _exit;

// Echoing
/**
* Prints content to stdout with a trailing newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values
Expand Down Expand Up @@ -768,7 +794,7 @@ declare global {
var __filename: string;
var __dirname: string;
var dirname: typeof path.dirname;
var exit: typeof process.exit;
var exit: typeof _exit;
var error: typeof _error;
var echo: typeof _echo;
var printf: typeof _printf;
Expand Down
Loading