Módulo módulo básico

módulo child_process

módulo de gestión de subprocesos

Citación:

1 2
var child_process = require("child_process"); var child = child_process.spawn("ls");

Al crear un proceso secundario, la opción options.stdio se usa para configurar la canalización establecida entre el proceso principal y el proceso secundario. De forma predeterminada, stdin, stdout y stderr del proceso secundario se redireccionan aChildProcessLos flujos stdin, stdout y stderr correspondientes en el objeto. Esto es equivalente a establecer options.stdio en ['tubería', 'tubería', 'tubería'].

Para mayor comodidad, options.stdio puede ser una de las siguientes cadenas:

  • 'tubería': Equivalente a ['tubería', 'tubería', 'tubería'] (predeterminado).
  • 'ignorar': Equivalente a ['ignorar', 'ignorar', 'ignorar'].
  • 'heredar': Equivalente a ['heredar', 'heredar', 'heredar'] o [0, 1, 2].
  • 'pty': Equivalente a ['pty', 'pty', 'pty']. Windows no es compatible.

De lo contrario, el valor de options.stdio debe ser una matriz (donde cada índice corresponde a un descriptor de archivo en el proceso secundario). Los descriptores de archivo 0, 1 y 2 corresponden a stdin, stdout y stderr, respectivamente. Se pueden especificar otros descriptores de archivos para crear otras canalizaciones entre los procesos principal y secundario. El valor puede ser uno de los siguientes:

  1. 'tubería': crea una tubería entre el proceso secundario y el proceso principal. El extremo principal de la canalización se expone al proceso principal como un atributo stdio[fd] en el objeto child_process. Las canalizaciones creadas para los descriptores de archivo 0, 1 y 2 también están disponibles como stdin, stdout y stderr, respectivamente.
  2. 'ignorar': indica a fibjs que ignore los descriptores de archivo en los procesos secundarios. Si bien fibjs siempre abrirá los descriptores de archivo 0, 1 y 2 para sus procesos generados, establecer los descriptores de archivo en 'ignorar' hace que fibjs abra /dev/null y lo adjunte al descriptor de archivo del niño.
  3. 'heredar': transmitir el stdio correspondiente hacia o desde el proceso principal. En las tres primeras posiciones, esto equivale aprocess.stdin,process.stdoutyprocess.stderr. En cualquier otra posición, equivale a 'ignorar'.
  4. 'pty': El subproceso se ejecutará en una terminal virtual. Solo stdin y stdout están disponibles en este momento.
  5. Enteros positivos: los valores enteros se interpretan como descriptores de archivo actualmente abiertos en el proceso principal. Se comparte con procesos secundarios, similar a compartir <Stream> Modo objeto. Los sockets entrantes no son compatibles con Windows.
  6. nulo o indefinido: utilice el valor predeterminado. Para los descriptores de archivo 0, 1 y 2 de stdio (en otras palabras, stdin, stdout y stderr), se crean canalizaciones. Para los descriptores de archivo 3 y superiores, el valor predeterminado es 'ignorar'.
1 2 3 4 5 6 7 8 9 10 11 12 13
const { spawn } = require('child_process'); // child process uses parent's stdio spawn('prg', [], { stdio: 'inherit' }); // child process uses parent's stderr spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });

Para los usuarios que usan nodejs al mismo tiempo, presten atención

  • La función de child_process.exec(command, args)fibjs es similar a la API del mismo nombre de nodejs, pero en Windows, cmd.exe no se usa automáticamente como entorno de ejecución del parámetro del comando;
  • child_process.[spawn|exec|execFile|run] de fibjs es una función de estilo asíncrono que integra sincronización/devolución de llamada:
    • Síncrono si el último argumento no es una función
    • asincrónico si se pasa una función como último argumento;
  • El resultado de retorno de child_process.[exec|execFile] de fibjs es un objeto, que es completamente diferente del objeto devuelto por la API de nodejs con el mismo nombre
  • fibjs no tiene la API correspondiente child_process.runen nodejs

función estática

spawn

Inicie un proceso secundario con el comando dado

1 2 3
static ChildProcess child_process.spawn(String command, Array args, Object options = {});

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // configure the group identity of the process "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Inicie un proceso secundario con el comando dado

1 2
static ChildProcess child_process.spawn(String command, Object options = {});

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

exec

Ejecuta un comando en el shell y almacena en búfer la salida. Cuando se ejecuta como devolución de llamada, la función devuelve el objeto de subproceso

1 2
static (Variant stdout, Variant stderr) child_process.exec(String command, Object options = {}) async;

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

  • (Variant stdout, Variant stderr), devuelve la salida stdio del proceso secundario

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

execFile

Ejecuta directamente el archivo especificado y almacena en búfer la salida. Cuando se ejecuta como una devolución de llamada, la función devolverá el objeto de proceso secundario

1 2 3
static (Variant stdout, Variant stderr) child_process.execFile(String command, Array args, Object options = {}) async;

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

  • (Variant stdout, Variant stderr), devuelve la salida stdio del proceso secundario

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Ejecuta directamente el archivo especificado y almacena en búfer la salida. Cuando se ejecuta como una devolución de llamada, la función devolverá el objeto de proceso secundario

1 2
static (Variant stdout, Variant stderr) child_process.execFile(String command, Object options = {}) async;

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

  • (Variant stdout, Variant stderr), devuelve la salida stdio del proceso secundario

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

fork

Ejecutar un módulo en un subproceso

1 2 3
static ChildProcess child_process.fork(String module, Array args, Object options = {});

Parámetros de llamada:

  • module: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Ejecutar un módulo en un subproceso

1 2
static ChildProcess child_process.fork(String module, Object options = {});

Parámetros de llamada:

  • module: Cadena, especifica el comando a ejecutar
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

run

Ejecute el archivo especificado directamente y devuelva el código de salida, cuando se ejecute como una devolución de llamada, la función devolverá el objeto de proceso secundario

1 2 3
static Integer child_process.run(String command, Array args, Object options = {}) async;

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

  • Integer, devuelve el código de salida del proceso hijo

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Ejecute el archivo especificado directamente y devuelva el código de salida, cuando se ejecute como una devolución de llamada, la función devolverá el objeto de proceso secundario

1 2
static Integer child_process.run(String command, Object options = {}) async;

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especifica los parámetros de creación

resultado devuelto:

  • Integer, devuelve el código de salida del proceso hijo

El contenido admitido de las opciones es el siguiente:

1 2 3 4 5 6 7 8 9
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }