Execute a command line binary with Node.js

后端 未结 12 2213
星月不相逢
星月不相逢 2020-11-22 01:39

I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplis

12条回答
  •  清酒与你
    2020-11-22 02:04

    You can use execa.

    For example, as a promise:

    const execa = require('execa')
    
    execa('cat *.js bad_file').then(
      (childProcessResult) => {
        //onFulfilled
        console.log('Success!', childProcessResult)
      },
      (childProcessResult) => {
        //onRejected
        console.log('Error!', childProcessResult)
      }
    )
    

    Execa improves child_process methods with:

    • Promise interface.
    • Strips the final newline from the output so you don't have to do stdout.trim().
    • Supports shebang binaries cross-platform.
    • Improved Windows support.
    • Higher max buffer. 100 MB instead of 200 KB.
    • Executes locally installed binaries by name.
    • Cleans up spawned processes when the parent process dies.
    • Get interleaved output from stdout and stderr similar to what is printed on the terminal. (Async only)
    • Can specify file and arguments as a single string without a shell
    • More descriptive errors.

提交回复
热议问题