child_process.exec(command[, options][, callback])
| 版本 | 變化 | 
|---|---|
| v15.4.0 | 添加了AbortSignal 支持。  | 
| v16.4.0、v14.18.0 | 
  | 
| v8.8.0 | 現在支持  | 
| v0.1.90 | 添加於:v0.1.90  | 
參數
command<string> 要運行的命令,參數以空格分隔。options<Object>cwd<string> | <URL> 子進程的當前工作目錄。 默認:process.cwd()。env<Object> 環境鍵值對。 默認:process.env。encoding<string> 默認:'utf8'shell<string> Shell 用來執行命令。請參閱 Shell requirements 和 Default Windows shell 。 默認:'/bin/sh'在 Unix 上,process.env.ComSpec在 Windows 上。signal<AbortSignal> 允許使用 AbortSignal 中止子進程。timeout<number> 默認:0maxBuffer<number>stdout 或 stderr 上允許的最大數據量(以字節為單位)。如果超過,則終止子進程並截斷任何輸出。請參閱警告maxBuffer和 Unicode.默認:1024 * 1024.killSignal<string> | <integer> 默認:'SIGTERM'uid<number> 設置進程的用戶身份(參見)。setuid(2)gid<number> 設置進程的組標識(參見)。setgid(2)windowsHide<boolean> 隱藏通常在 Windows 係統上創建的子進程控製台窗口。 默認:false。
callback<Function>進程終止時使用輸出調用。- 返回: <ChildProcess>
 
生成一個 shell,然後在該 shell 中執行 command,緩衝任何生成的輸出。傳遞給 exec 函數的 command 字符串由 shell 直接處理,特殊字符(根據 shell 不同)需要相應處理:
const { exec } = require('node:child_process');
exec('"/path/to/test file/test.sh" arg1 arg2');
// Double quotes are used so that the space in the path is not interpreted as
// a delimiter of multiple arguments.
exec('echo "The \\$HOME variable is $HOME"');
// The $HOME variable is escaped in the first instance, but not in the second.
切勿將未經處理的用戶輸入傳遞給此函數。任何包含 shell 元字符的輸入都可用於觸發任意命令執行。
如果提供了 callback 函數,則使用參數 (error, stdout, stderr) 調用它。成功後,error 將是 null 。出錯時,error 將是   的一個實例。 Error error.code 屬性將是進程的退出代碼。按照慣例,0 以外的任何退出代碼都表示錯誤。 error.signal 將是終止進程的信號。
傳遞給回調的 stdout 和 stderr 參數將包含子進程的 stdout 和 stderr 輸出。默認情況下,Node.js 會將輸出解碼為 UTF-8 並將字符串傳遞給回調。 encoding 選項可用於指定用於解碼 stdout 和 stderr 輸出的字符編碼。如果 encoding 是 'buffer' 或無法識別的字符編碼,則將 Buffer 對象傳遞給回調。
const { exec } = require('node:child_process');
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stderr}`);
});
如果 timeout 大於 0 ,如果孩子運行時間超過 timeout 毫秒,則父母將發送由 killSignal 屬性標識的信號(默認為 'SIGTERM' )。
與  POSIX 係統調用不同,exec(3) child_process.exec() 不會替換現有進程,而是使用 shell 來執行命令。
如果此方法作為其   ed 版本調用,它會為具有 util.promisify() stdout 和 stderr 屬性的 Object 返回 Promise。返回的ChildProcess 實例作為child 屬性附加到Promise。如果發生錯誤(包括導致退出代碼不是 0 的任何錯誤),將返回一個被拒絕的 promise,並在回調中給出相同的 error 對象,但具有兩個附加屬性 stdout 和 stderr 。
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
如果啟用了 signal 選項,則在相應的 AbortController 上調用 .abort() 與在子進程上調用 .kill() 類似,隻是傳遞給回調的錯誤將是 AbortError :
const { exec } = require('node:child_process');
const controller = new AbortController();
const { signal } = controller;
const child = exec('grep ssh', { signal }, (error) => {
  console.log(error); // an AbortError
});
controller.abort();
相關用法
- Node.js child_process.execFile(file[, args][, options][, callback])用法及代碼示例
 - Node.js child_process.spawn(command[, args][, options])用法及代碼示例
 - Node.js child_process.fork(modulePath[, args][, options])用法及代碼示例
 - Node.js certificate.verifySpkac(spkac[, encoding])用法及代碼示例
 - Node.js console.timeEnd()用法及代碼示例
 - Node.js crypto.randomFill()用法及代碼示例
 - Node.js crypto.createHmac()用法及代碼示例
 - Node.js crypto.randomFillSync(buffer[, offset][, size])用法及代碼示例
 - Node.js console.countReset()用法及代碼示例
 - Node.js cluster.worker用法及代碼示例
 - Node.js crypto.constants用法及代碼示例
 - Node.js crypto.randomInt([min, ]max[, callback])用法及代碼示例
 - Node.js crypto.publicEncrypt()用法及代碼示例
 - Node.js console.trace()用法及代碼示例
 - Node.js console.timeLog()用法及代碼示例
 - Node.js console.timeStamp()用法及代碼示例
 - Node.js crypto.publicDecrypt()用法及代碼示例
 - Node.js console.dir()用法及代碼示例
 - Node.js crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)用法及代碼示例
 - Node.js console.log()用法及代碼示例
 - Node.js crypto.createHash()用法及代碼示例
 - Node.js crypto.hkdfSync()用法及代碼示例
 - Node.js crypto.randomFillSync()用法及代碼示例
 - Node.js crypto.checkPrime()用法及代碼示例
 - Node.js clienthttp2session.request()用法及代碼示例
 
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 child_process.exec(command[, options][, callback])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
