首頁 > web前端 > js教程 > 如何在 Node.js 中執行命令列二進位和檔案?

如何在 Node.js 中執行命令列二進位和檔案?

Patricia Arquette
發布: 2024-12-25 09:20:11
原創
961 人瀏覽過

How Can I Execute Command Line Binaries and Files in Node.js?

在 Node.js 中執行命令列二進位檔案

在 Node.js 中,執行命令列二進位檔案的過程是透過 child_process 模組處理的。無論您需要執行指令還是使用流處理程序 I/O,都有符合您要求的選項。

非同步執行

使用緩衝區執行命令

執行命令並將其完整輸出作為緩衝區獲取,請使用child_process.exec():

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

exec('command', (error, stdout, stderr) => {
  // command output is in stdout
});
登入後複製

Streaming輸出

如果需要用流處理進程I/O,請使用child_process.spawn():

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

const child = spawn('command', ['args']);

child.stdout.on('data', (chunk) => {
  // output will be here in chunks
});
登入後複製

同步執行

Node.js 也支援同步spawn和執行方法。這些方法不會傳回 ChildProcess 的實例:

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

let stdout = execSync('command');
登入後複製

執行檔

如果您需要執行檔案而不是指令,請使用 child_process.execFile():

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

execFile('file', ['args'], (error, stdout, stderr) => {
  // command output is in stdout
});
登入後複製

以上是如何在 Node.js 中執行命令列二進位和檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板