Execute a command line binary with Node.js

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

    @hexacyanide's answer is almost a complete one. On Windows command prince could be prince.exe, prince.cmd, prince.bat or just prince (I'm no aware of how gems are bundled, but npm bins come with a sh script and a batch script - npm and npm.cmd). If you want to write a portable script that would run on Unix and Windows, you have to spawn the right executable.

    Here is a simple yet portable spawn function:

    function spawn(cmd, args, opt) {
        var isWindows = /win/.test(process.platform);
    
        if ( isWindows ) {
            if ( !args ) args = [];
            args.unshift(cmd);
            args.unshift('/c');
            cmd = process.env.comspec;
        }
    
        return child_process.spawn(cmd, args, opt);
    }
    
    var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])
    
    // Use these props to get execution results:
    // cmd.stdin;
    // cmd.stdout;
    // cmd.stderr;
    

提交回复
热议问题