Guest User

shelljs exec async

a guest
May 9th, 2021
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*eslint complexity: ["error", 9]*/
  2. export const handleShellResponse = (
  3.   code: number | null,
  4.   stdout: string | null,
  5.   stderr: string | null,
  6.   command: string,
  7.   settings: ShellExecOptions,
  8.   resolve: (value?: ShellExecSuccess) => void,
  9.   reject: (value?: ShellExecError) => void,
  10. ): void => {
  11.   switch (code) {
  12.     case 0: // success
  13.       return resolve(
  14.         new ShellExecSuccess(code, stdout, stderr, command, settings),
  15.       );
  16.     // If there is an error then reject
  17.     case null: // timeout
  18.       return reject(
  19.         new ShellExecTimeoutError(code, stdout, stderr, command, settings),
  20.       );
  21.     case 127: // not-found
  22.       return reject(
  23.         new ShellExecNotFoundError(code, stdout, stderr, command, settings),
  24.       );
  25.     case 1: // Catch-all
  26.     case 2: // Misuse of shell builtins (according to Bash documentation)
  27.     case 126: // Command invoked cannot execute
  28.     case 128: // Invalid argument to exit
  29.     case 130: // Script terminated by Control-C
  30.     default:
  31.       return reject(
  32.         new ShellExecError(code, stdout, stderr, command, settings),
  33.       );
  34.   }
  35. };
  36.  
  37. export const shellExec = async (
  38.   command: string,
  39.   settings: ShellExecOptions = SHELL_DEFAULT_SETTINGS,
  40. ): Promise<ShellExecResponse> => {
  41.   return new Promise((resolve, reject) => {
  42.     shell.exec(
  43.       command,
  44.       settings,
  45.       (code: number | null, stdout: string | null, stderr: string | null) => {
  46.         handleShellResponse(
  47.           code,
  48.           stdout,
  49.           stderr,
  50.           command,
  51.           settings,
  52.           resolve,
  53.           reject,
  54.         );
  55.       },
  56.     );
  57.   });
  58. };
Advertisement
Add Comment
Please, Sign In to add comment