簡體   English   中英

如何獲取在nodejs中使用child_process執行的命令的輸出?

[英]How to get the output of command executed using child_process in nodejs?

我是 node js 的新手,我想在 node js 中執行一個命令,並希望將命令的運行狀態顯示到終端以及一些日志文件中。

// Displaying the output in terminal but I am not able to access child.stdout
const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: 'inherit',
      encoding: 'utf-8',
    });

// Pushing the output to file but not able to do live interaction with terminal
const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: 'pipe',
      encoding: 'utf-8',
    });

兩者都可以嗎? 請在這件事上給予我幫助?

提前致謝。

您可以為 stdin、stdout 和 stderr 指定單獨的選項:

const child = spawn(command,[], {
      shell: true,
      cwd: process.cwd(),
      env: process.env,
      stdio: ['inherit', 'pipe', 'pipe'],
      encoding: 'utf-8',
    });

這樣子進程繼承了標准輸入,你應該能夠與它進行交互。 子進程使用 stdout(和 stderr)管道,您可以將輸出寫入文件。 由於子進程沒有將輸出發送到終端,因此您需要自己將輸出寫入終端。 這可以通過管道輕松完成:

// Pipe child stdout to process stdout (terminal)...
child.stdout.pipe(process.stdout);

// ...and do something else with the data.
child.stdout.on('data', (data) => ...);

這可能只有在子進程是一個簡單的命令行程序並且沒有基於文本的高級 UI 時才能正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM