我從Typoro中學到的Child Process知識點(三)

Typora中可以通過配置圖片上傳服務的自定義命令,在自定義服務中上傳圖片并打印上傳結果,當插入圖片時就會將本地圖片上傳,并替換成網(wǎng)絡圖片地址。

file-uploader-cli為例, 配置fuc(windows)或/usr/local/bin/node /usr/local/bin/fuc(MacOS)之后,插入圖片就會調用file-uploader-cli并傳入本地圖片地址,圖片上傳完成Typora會捕獲到console打印的網(wǎng)絡地址并替換本地圖片。

image

Typora是怎么獲取到file-uploader-cli中console打印結果呢?

Node.js中可以通過chid process創(chuàng)建子進程,在子進程中執(zhí)行任務,并捕獲子進程stdout輸出。

Child Process

我們先了解一下Node.js創(chuàng)建方式子進程有哪幾種方式,child process提供了spawn、exec、execFile、fork四種方式來創(chuàng)建異步子進程,execFile、exec、spawn有對應的同步子進程(會阻塞 Node.js 事件循環(huán),直到子進程退出或終止),exec、execFile、fork底層都是通過spawn/spawnSync來實現(xiàn)的。

首先了解一個概念:stdin,stdout,stderr是啥?

用于輸入、輸出和錯誤輸出的標準流,一般是從鍵盤讀取,而將標準輸出和標準錯誤打印到屏幕上。每個進程都會有相應的文件描述符綁定到stdin,stdout,stderr用來獲取輸入輸出。

stdout和stderr輸出管道的容量是有限的(且特定于平臺),如果子進程在沒有捕獲輸出的情況下寫入標準輸出超過該限制,則子進程會阻塞等待管道緩沖區(qū)接受更多數(shù)據(jù)。

exec和execFile可以通過maxBuffer指定stdout和stderr上允許的最大數(shù)據(jù)量(以字節(jié)為單位,默認值: 1024 * 1024),超出容量則子進程將終止并截斷任何輸出。

不同方式的實現(xiàn)

創(chuàng)建一個打印輸出的文件,我們來獲取執(zhí)行print.js的輸出。

#!/usr/bin/env node
// print.js
console.log('http://baidu.com')
spawn

先看一個官方的小示例

// spawn、fork、exec和execFile方法都返回 ChildProcess 實例, 實現(xiàn)了EventEmitter API,允許父進程·調用的監(jiān)聽器函數(shù)
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '.']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
spawn實現(xiàn)讀取stdout輸出數(shù)據(jù)

創(chuàng)建一個test.js文件來獲取輸出,stdout輸出流的緩沖機制,數(shù)據(jù)量大時捕獲會多次接收到數(shù)據(jù)。

#!/usr/bin/env node
const { spawn } = require('child_process');
const [command, ...rest] = process.argv.slice(2)
const sp = spawn(command, rest);
let output = [],errorOutput = [];

sp.stdout.on('data', (data) => {
    output.push(data)
});

sp.stderr.on('data', (data) => {
    errorOutput.push(data)
});

sp.on('close', (code) => {
  // 默認獲取到的是Buffer,轉成字符
  const outputStr = code === 0 ? Buffer.concat(output).toString() : Buffer.concat(errorOutput).toString()
  // 處理結尾增加的空行
  const printText = outputStr.toString().split(/\r?\n/)[0]
  // print.js輸出的內容
  console.log('獲取到的輸出:',printText)
});

為文件添加執(zhí)行權限, 并執(zhí)行:

chmod +x test.js
./test.js node ./print.js
# or
node test.js node ./print.js

我們就可以看到test.js捕獲到子進程的輸出了。

如果為print.js創(chuàng)建了軟連接,也可直接使用./test.js print

exec

exec 會創(chuàng)建一個新的shell,在shell中執(zhí)行,執(zhí)行完成后會將stdout和stderr傳入回調,所以stdout會一次獲取到子進程所有輸出數(shù)據(jù)。

exec實現(xiàn)讀取stdout輸出數(shù)據(jù)
#!/usr/bin/env node
const { exec } = require('child_process');

exec(`${process.argv.slice(2).join(' ')}`, (error, stdout, stderr) => {
    if (error) {
      console.error(error);
      return;
    }
    // 默認獲取到的是Buffer,轉成字符  處理結尾增加的空行,
    const printText = stdout.toString().split(/\r?\n/)[0]
    console.log(printText);
});

execSync:

execSync和exec不同之處在于:execSync子進程完全關閉之前不會返回。

#!/usr/bin/env node
const { execSync } = require('child_process');
const result = execSync(`${process.argv.slice(2).join(' ')}`);
const printText = result.toString().split(/\r?\n/)[0]
console.log(printText)
execFile

和exec類似,不過不會創(chuàng)建新的shell,指定的可執(zhí)行文件作為新進程,exec也是通過調用execFile來實現(xiàn)的。

fork

創(chuàng)建新的 Node.js 進程并使用建立的 IPC 通信通道(其允許在父子進程之間發(fā)送消息)

其他

pipe管道打印輸出

在創(chuàng)建的子進程中執(zhí)行任務,比如創(chuàng)建子進程通過npm為項目安裝依賴,這個時候子進程執(zhí)行信息需要輸出到父進程中打印,用戶才能看到執(zhí)行進度和結果。

// 父進程監(jiān)聽子進程輸出并打印
sp.stdout.on('data', (data) => {
    console.log(data)
});

sp.stderr.on('data', (data) => {
    console.log(data)
});

stdout和stderr屬于標準輸出流,可以使用Steam API,通過pipe管道傳遞到父進程中。

sp.stdout.pipe(process.stdout);
sp.stderr.pipe(process.stderr);

也可以通過指定 option.stdio 配置父進程和子進程之間建立的管道。

const { spawn } = require('child_process');
// 子進程將使用父進程的標準輸入輸出。
spawn('prg', [], { stdio: 'inherit' });
// 衍生僅共享標準錯誤的子進程。
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
// 打開額外的文件描述符=4,以與呈現(xiàn) startd 風格界面的程序進行交互。
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });

Windows和類Unix(Mac,Linux,Unix)區(qū)別

child_process.execFile() 在類Unix系統(tǒng)上執(zhí)行效率可能快,因為不用創(chuàng)建新的shell。但是在Windows上.bat.cmd文件在沒有終端的情況下不能單獨執(zhí)行,所以不能使用execFile??梢酝ㄟ^spawn傳入shell配置調用,或調用cmd.exe并傳入.bat.cmd文件。

使用cross-spawnexeca來幫我們執(zhí)行命令,解決跨平臺問題,更優(yōu)雅調用child_process方法

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容