programing

Node.js를 사용하여 명령줄 바이너리를 실행합니다.

minecode 2023. 1. 14. 09:39
반응형

Node.js를 사용하여 명령줄 바이너리를 실행합니다.

Ruby에서 Node.js로 CLI 라이브러리를 이식하는 중입니다.제 코드로 필요에 따라 여러 개의 서드파티 바이너리를 실행합니다.노드에서의 최적의 실행 방법을 알 수 없습니다.

다음은 Prince X라고 부르는 루비의 예입니다.파일을 PDF로 변환하기 위한 ML:

cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")

노드의 동등한 코드는 무엇입니까?

더 새로운 버전의 Node.js(v8.1.4)에서는 이벤트와 콜은 이전 버전과 비슷하거나 동일하지만 새로운 표준 언어 기능을 사용하는 것이 좋습니다.예:

버퍼링된 비스트림 형식의 출력(한 번에 얻을 수 있음)의 경우 다음을 사용합니다.

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

Promise와 함께 사용할 수도 있습니다.

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

데이터를 청크로 점진적으로 수신하려면(스트림으로 출력) 다음을 사용합니다.

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

이들 기능에는 모두 동기 대응 기능이 있습니다.의 예:

const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

또, 다음과 같이 합니다.

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);

주의: 다음 코드는 아직 사용할 수 있지만 주로 ES5 이전 사용자를 대상으로 합니다.

Node.js를 사용한 하위 프로세스 산란 모듈은 문서(v5.0.0)에 잘 설명되어 있습니다.명령을 실행하여 완전한 출력을 버퍼로 가져오려면 다음 명령을 사용합니다.

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

대량의 출력이 예상되는 경우 등 스트림에서 처리 프로세스 I/O를 사용해야 하는 경우 다음을 사용합니다.

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

명령어가 아닌 파일을 실행하는 경우 와 거의 동일한 파라미터를 사용할 수 있습니다.spawn4번째 .예를 들어, 4번째 콜백파라미터는 「4」입니다.exec출력 버퍼를 취득합니다.을 사용하다

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

v0.11.12 이후 노드는 동기화를 지원하게 되었습니다.spawn ★★★★★★★★★★★★★★★★★」exec위에서 설명한 모든 메서드는 비동기 방식이며 동기식 메서드가 있습니다.이 문서의 설명서는 여기에서 찾을 수 있습니다.스크립팅에는 유용하지만 자녀 프로세스를 비동기적으로 생성하기 위해 사용되는 방식과 달리 동기 메서드는 인스턴스를 반환하지 않습니다.

JS ® JSv15.8.0, LTSv14.15.4 , , , , 입니다.v12.20.1 2월--- 2021년 2월

비동기 방식(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 }` );
} );

비동기 방식(Windows):

'use strict';

const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
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}` ) );

동기화:

'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() }` );

Node.js v15.8.0 매뉴얼에서

Node.js v14.15.4 매뉴얼 및 Node.js v12.20.1 매뉴얼도 마찬가지입니다.

child_process를 찾고 있습니다.이그제큐티브

다음은 예를 제시하겠습니다.

const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
    (error, stdout, stderr) => {
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
});

버전 4 이후 가장 가까운 대안은child_process.execSync 방법:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

⚠180 유의사항execSync콜은 이벤트루프를 차단합니다.

const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})

상위 답변과 매우 유사하지만 동기화된 것을 원하는 경우 이 방법을 사용할 수 있습니다.

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));

이제 다음과 같이 (노드 v4에서) shelljs를 사용할 수 있습니다.

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version');

인스톨

npm install shelljs

https://github.com/shelljs/shelljs 를 참조해 주세요.

Unix/windows를 쉽게 다룰 수 있도록 CLI 도우미를 작성했습니다.

Javascript:

define(["require", "exports"], function (require, exports) {
    /**
     * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
     * Requires underscore or lodash as global through "_".
     */
    var Cli = (function () {
        function Cli() {}
            /**
             * Execute a CLI command.
             * Manage Windows and Unix environment and try to execute the command on both env if fails.
             * Order: Windows -> Unix.
             *
             * @param command                   Command to execute. ('grunt')
             * @param args                      Args of the command. ('watch')
             * @param callback                  Success.
             * @param callbackErrorWindows      Failure on Windows env.
             * @param callbackErrorUnix         Failure on Unix env.
             */
        Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
            if (typeof args === "undefined") {
                args = [];
            }
            Cli.windows(command, args, callback, function () {
                callbackErrorWindows();

                try {
                    Cli.unix(command, args, callback, callbackErrorUnix);
                } catch (e) {
                    console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
                }
            });
        };

        /**
         * Execute a command on Windows environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.windows = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(process.env.comspec, _.union(['/c', command], args));
                callback(command, args, 'Windows');
            } catch (e) {
                callbackError(command, args, 'Windows');
            }
        };

        /**
         * Execute a command on Unix environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.unix = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(command, args);
                callback(command, args, 'Unix');
            } catch (e) {
                callbackError(command, args, 'Unix');
            }
        };

        /**
         * Execute a command no matters what's the environment.
         *
         * @param command   Command to execute. ('grunt')
         * @param args      Args of the command. ('watch')
         * @private
         */
        Cli._execute = function (command, args) {
            var spawn = require('child_process').spawn;
            var childProcess = spawn(command, args);

            childProcess.stdout.on("data", function (data) {
                console.log(data.toString());
            });

            childProcess.stderr.on("data", function (data) {
                console.error(data.toString());
            });
        };
        return Cli;
    })();
    exports.Cli = Cli;
});

원본 파일 형식:

 /**
 * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
 * Requires underscore or lodash as global through "_".
 */
export class Cli {

    /**
     * Execute a CLI command.
     * Manage Windows and Unix environment and try to execute the command on both env if fails.
     * Order: Windows -> Unix.
     *
     * @param command                   Command to execute. ('grunt')
     * @param args                      Args of the command. ('watch')
     * @param callback                  Success.
     * @param callbackErrorWindows      Failure on Windows env.
     * @param callbackErrorUnix         Failure on Unix env.
     */
    public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
        Cli.windows(command, args, callback, function () {
            callbackErrorWindows();

            try {
                Cli.unix(command, args, callback, callbackErrorUnix);
            } catch (e) {
                console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
            }
        });
    }

    /**
     * Execute a command on Windows environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(process.env.comspec, _.union(['/c', command], args));
            callback(command, args, 'Windows');
        } catch (e) {
            callbackError(command, args, 'Windows');
        }
    }

    /**
     * Execute a command on Unix environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(command, args);
            callback(command, args, 'Unix');
        } catch (e) {
            callbackError(command, args, 'Unix');
        }
    }

    /**
     * Execute a command no matters what's the environment.
     *
     * @param command   Command to execute. ('grunt')
     * @param args      Args of the command. ('watch')
     * @private
     */
    private static _execute(command, args) {
        var spawn = require('child_process').spawn;
        var childProcess = spawn(command, args);

        childProcess.stdout.on("data", function (data) {
            console.log(data.toString());
        });

        childProcess.stderr.on("data", function (data) {
            console.error(data.toString());
        });
    }
}

Example of use:

    Cli.execute(Grunt._command, args, function (command, args, env) {
        console.log('Grunt has been automatically executed. (' + env + ')');

    }, function (command, args, env) {
        console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');

    }, function (command, args, env) {
        console.error('------------- Unix "' + command + '" command failed too. ---------------');
    });

이 경량 사용npm패키지:system-commands

여기 보세요.

다음과 같이 Import합니다.

const system = require('system-commands')

다음과 같은 명령을 실행합니다.

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

의존관계를 개의치 않고 약속을 사용하려는 경우, 다음과 같이 하십시오.

설치

npm install child-process-promise --save

exec 사용방법

var exec = require('child-process-promise').exec;
 
exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

용법을 만들어 내다

var spawn = require('child-process-promise').spawn;
 
var promise = spawn('echo', ['hello']);
 
var childProcess = promise.childProcess;
 
console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});
 
promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

ECMAScript 모듈import...from구문

import {exec} from 'child-process-promise';
let result = await exec('echo hi');
console.log(result.stdout);

@cyanide의 대답은 거의 완전한 것이다.Windows 명령어prince그럴 수도 있겠지요prince.exe,prince.cmd,prince.bat아니면 그냥prince(보석이 어떻게 번들 되는지는 모르겠지만, npm bins에는 sh 스크립트와 배치 스크립트가 포함되어 있습니다.npm그리고.npm.cmdUnix 및 Windows에서 실행되는 휴대용 스크립트를 작성하려면 적절한 실행 파일을 생성해야 합니다.

다음은 간단하지만 휴대 가능한 sean 기능입니다.

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;

언급URL : https://stackoverflow.com/questions/20643470/execute-a-command-line-binary-with-node-js

반응형