97 votos

ejecutar una línea de comandos binarios en el nodo/js

Estoy en el proceso de trasladar un CLI biblioteca de Ruby a NodeJS. En mi código que ejecute varias terceras partes de los binarios cuando sea necesario. No estoy seguro de que la mejor forma de lograr esto en el nodo/js.

He aquí un ejemplo en Ruby donde puedo llamar princexml para convertir a pdf:

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

Necesito hacer lo mismo nodo/js.

168voto

hexacyanide Puntos 15723

Usted debe echar un vistazo a la documentación. Para ejecutar un comando y recuperar su salida completa como un tampón, uso child_process.exec:

var exec = require('child_process').exec;
exec('prince -v builds/pdf/book.html -o builds/pdf/book.pdf', function (error, stdout, stderr) {
  // output is in stdout
});

Para ejecutar un comando y obtener una salida como arroyos, uso child_process.spawn:

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 here
});

14voto

Andrei Karpushonak Puntos 2364

Estás buscando child_process.exec

Aquí está el ejemplo:

var exec = require('child_process').exec,
    child;

child = exec('cat *.js bad_file | wc -l',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

8voto

Vadorequest Puntos 923

Acabo de escribir un Cli ayuda para lidiar con Unix/windows fácilmente.

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;

});

Manuscrito original del archivo de código fuente:

/**
 * 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());
    });
}

}

Ejemplo de uso:

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

Iteramos.com

Iteramos es una comunidad de desarrolladores que busca expandir el conocimiento de la programación mas allá del inglés.
Tenemos una gran cantidad de contenido, y también puedes hacer tus propias preguntas o resolver las de los demás.

Powered by:

X