Execute a command line binary with Node.js

后端 未结 12 2509
星月不相逢
星月不相逢 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:06

    Node JS v13.9.0, LTS v12.16.1, and v10.19.0 --- Mar 2020

    Async method (Unix):

    'use strict';
    
    const { spawn } = require( 'child_process' );
    const ls = spawn( 'ls', [ '-lh', '/usr' ] );
    
    ls.stdout.on( 'data', data => {
        console.log( `stdout: ${data}` );
    } );
    
    ls.stderr.on( 'data', data => {
        console.log( `stderr: ${data}` );
    } );
    
    ls.on( 'close', code => {
        console.log( `child process exited with code ${code}` );
    } );
    


    Async method (Windows):

    'use strict';
    
    const { spawn } = require( 'child_process' );
    const dir = spawn('cmd', ['/c', 'dir'])
    
    dir.stdout.on( 'data', data => console.log( `stdout: ${data}` ) );
    dir.stderr.on( 'data', data => console.log( `stderr: ${data}` ) );
    dir.on( 'close', code => console.log( `child process exited with code ${code}` ) );
    


    Sync:

    'use strict';
    
    const { spawnSync } = require( 'child_process' );
    const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );
    
    console.log( `stderr: ${ls.stderr.toString()}` );
    console.log( `stdout: ${ls.stdout.toString()}` );
    

    From Node.js v13.9.0 Documentation

    The same goes for Node.js v12.16.1 Documentation and Node.js v10.19.0 Documentation

提交回复
热议问题