如何在 Node.js 中執行 Shell 命令

以下介紹如何在 Node.js 腳本中執行 Shell 命令。 首先,從 child_process 中導入 child 模組: import * as child from 'node:child_process'; // 或者 const child = require('node:child_process'); 然後,你可以像這樣調用 child.exec(): child.exec(`mkdir test`);

從 Node.js 腳本中調用 ImageOptim macOS 應用程式

平常在我的 Node.js 腳本中,我通常使用 sharp 來優化圖片。 但有時候我喜歡使用 ImageOptim macOS 應用程式 來通過圖形界面優化圖片。 這次我需要從一個 Node.js 腳本中啟動它。 下面是我的做法。 首先我導入了內建的 child_process Node 模組: import * as child from 'node:child_process' 然後我這樣調用它來優化特定文件夾中的所有圖片: const images_folder = './img' child.exec(`open -a ImageOptim ${images_folder}`) 這樣就會啟動該應用程式,你可以看到它的用戶界面,這沒什麼大不了的。 需要注意的是,這僅在你安裝了該應用程式的情況下才能正常工作。