SoFunction
Updated on 2025-04-09

How to execute shell commands in nodejs script

Official Documentation:

Chinese Documentation:child_process - child process

Use the built-in child_process module to execute shell commands. This module provides exec, execFile, spawn and other methods to start a child process and execute commands

1: Exec method executes shell command

1. Note:

  • The exec method is to cache the entire command output into memory and return it at once after the execution is completed, so it is suitable for executing smaller commands.
  • The callback function of the exec method will only be called after the command is executed [a persistent command will cause the callback function to not be executed]

Point 2_Example:

npm run dev

The command will be run all the time, and the callback function of the exec method will only be called after the command is completed, resulting in your callback function not returning.

2. Advantages and features:

  • The advantages are that they are simple and easy to use, convenient to execute simple commands, and can directly obtain command output;
  • For blocking calls, when the command output is large, it may cause the execution of the blocking program and even cause the program to crash.

3. Syntax format

exec( 'Order',optionObject, Callback functioncallback);

4. Option object properties

  • cwd <string> The current working directory of the child process.
  • env <Object> Environment variable key-value pair.
  • encoding <string> defaults to 'utf8'.
  • shell <string> The shell that executes the command. The default is ‘/bin/sh’ on UNIX and the default is ’ on Windows. For details, see the requirements of Shell and the default Shell of Windows.
  • timeout <number> defaults to 0.
  • maxBuffer <number> stdout or stderr allows maximum number of bytes. The default is 200*1024. If the limit is exceeded, the child process will be terminated. See maxBuffer and Unicode for details.
  • killSignal <string> | <integer> defaults to ‘SIGTERM’.
  • uid<number> sets the user ID of the process, see setuid(2) for details.
  • gid<number> sets the group identifier of the process, see setgid(2) for details.
  • windowsHide <boolean> The console window for hidden child processes is often used in Windows systems. Default is false.

5. _Example:

Nodejs – Identifies the operating system platform on which the process runs:

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

 // It is to make a simple `judgment` which command line` should be used to execute the command in the execution environment; //: Identify the operating system platform on which the process runs // Return value: ‘aix’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, ‘win32’ 
exec('ls -la',{shell: === 'win32'}, (error, stdout, stderr) =&gt; {
  if (error) {
    (`An execution error: ${error}`);
    return;
  }
  (`stdout: ${stdout}`);
  (`stderr: ${stderr}`);
});

The callback function has three parameters:

error, stdout and stderr:

  • errorIndicates an error occurred when executing the command;
  • stdoutRepresents the standard output of the command;
  • stderrIndicates the standard error output of the command;

Two: spawn method Execute shell command

1. Note:

  • The command parameter executed by the spawn method should be an Array.
  • This can avoid shell injection attacks.
// The command parameter should be an array ['-la']const ls = spawn('ls', ['-la'],{shell: === 'win32'},);

2. Advantages and features:

The spawn method returns the standard output and standard error stream of the child process in real time, which is suitable for executing large amounts of data or long-running commands [such as npm run dev];

Execute asynchronously, data can be processed immediately when the command outputs, and the execution of the program will not be blocked;

You can flexibly configure the input and output of subprocesses, environment variables and other options

3. _Syntax format:

const ls = spawn(OrderString, Order参数Array,optionObject);

('data', (data) =&gt; {
  (`stdout: ${data}`);
});

('data', (data) =&gt; {
  (`stderr: ${data}`);
});

('close', (code) =&gt; {
  (`Subprocess exit code:$[code]`);
});

4. Option object properties

  • cwd <string> The current working directory of the child process.
  • env<Object> environment variable key-value pair.
  • argv0 <string> explicitly sets the value of argv[0] to be sent to the child process. If not specified, set to command.
  • stdio<Array> | <string> child process's stdio configuration. (See details)
  • detached <boolean> Prepare to run the child process independently of the parent process. The specific behavior depends on the platform. (See [] for details)
  • uid <number> Sets the user ID of the process. (See setuid(2) for details)
  • gid <number> Sets the group identity of the process. (See setgid(2) for details)
  • shell <boolean> | <string> If true, run command in a shell. Use '/bin/sh' on UNIX, on - Windows. A different shell can be specified as a string. See [Shell Requirements][] and [Default Windows Shell][]. Default is false (no shell).
  • windowsVerbatimArguments <boolean> Determines whether to use escape parameters on Windows system. It will be automatically ignored on Linux platform, and this property will be automatically set to true when the command shell exists. Default value: false.
  • Is windowHide hidden in the subprocess console window that pops up by default under Windows system? The default is: false.

【4.1】 Detailed explanation of .stdio attribute: Configure the pipeline established between the parent process and the child process

  • Configure pipelines established between parent and child processes
  • Affects the output of shell commands, or node commands on the console

【Attribute value format <Array> | <string> 】

['pipe', 'pipe', 'pipe'] (default value)

Array elements correspond to positions:

  • - stdin[Standard input for commands]
  • - stdout[Standard output of command]
  • - stderr[Error occurred while executing commands]

'pipe', 'ignore', 'inherit

value effect
pipe Get it in the parent process through child_process.("data", () => {}) etc.
ignore The parent process gets null through the pipeline
inherit The child process will use the standard input output of the parent process
	('data', (data) =&gt; {
	  (`stdout: ${data}`);
	});
	
	('data', (data) =&gt; {
	  (`stderr: ${data}`);
	});
	
	('close', (code) =&gt; {
	  (`Subprocess exit code:$[code]`);
	});

5. Example:

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

// It is to make a simple `judgment` which command line` should be used to execute the command in the execution environment;//: Identify the operating system platform on which the process runs// Return value: ‘aix’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, ‘win32’
const ls = spawn('ls', ['-la'],{shell: === 'win32'},);

('data', (data) =&gt; {
  (`stdout: ${data}`);
});

('data', (data) =&gt; {
  (`stderr: ${data}`);
});

('close', (code) =&gt; {
  (`Subprocess exit code:$[code]`);
});

If you need to execute a complex shell command:

You can use the sh command and pass the command string as an argument to the sh command;

For example:

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

const command = 'ls -la | grep "example"';

const sh = spawn('sh', ['-c', command]);

('data', (data) =&gt; {
  (`stdout: ${data}`);
});

('data', (data) =&gt; {
  (`stderr: ${data}`);
});

('close', (code) =&gt; {
  (`Subprocess exit code:$[code]`);
});

In the example:

  • We use the sh command to execute a shell command containing the pipeline and pass the command string as an argument to the sh command.
  • In the spawn method, we use ['-c', command] as the parameter to start the sh command

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.