[英]Execute custom command on nodejs process
對於nodejs,我完全是新手。
我正在編寫一個自定義程序,我需要在其中添加一個手表,例如我從運行正常的 nodejs a.bat 文件開始,但我一直想知道是否可以在 shell 進程中控制命令的執行從外部?
就像我正在運行 shell 進程並手動輸入“刷新;重新加載資源_1”它工作正常,但使用 nodemon 我想為它添加一個監視,例如:我在 src 文件夾中編輯一個文件,我希望 nodejs 自動在 shell 進程中鍵入(或執行)“刷新;重新加載資源_1”等。我嘗試使用 exec,但它正在使用已經定義的命令,如“kill,dir”等等。
我正在研究 windows 機器。
提前致謝。
您可以寫入子進程的stdin
。 (前提是您在自己的節點腳本中啟動它。)
const { spawn } = require('child_process')
const child = spawn('some_command') // Start whatever process you want to talk to
// Pipe output so you can see it (you can also instead listen on the stdout/stderr streams
// and capture their output programmatically)
child.stdout.pipe(process.stdout)
child.stderr.pipe(process.stderr)
// Set encoding for input
child.stdin.setEncoding('utf-8')
// Write stuff into the process' stdin!
child.stdin.write('refresh; reload resource_1')
// Note that as long as the process is running and you keep the `child` variable around,
// you can keep writing into `child.stdin` even much later.
進一步閱讀:
如果您沒有自己啟動程序,但您想自動化之前已經運行的程序,那么它會變得更加棘手,並且 nodejs 不是最好的工具。 您可以使用 WinAPI 函數,但這是它自己的兔子洞,除非您真的需要它,否則現在進入它會浪費時間。
您可以利用 Node.js 的內置child_process
'use strict';
//Dependencies
const { exec, sapwn } = require('child_process');
//The command which you wish to run
//If you want to use PowerShell
//child = spawn("powershell.exe",["c:\\temp\\helloworld.ps1"]);
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
//Logging
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
請參考這里的官方文檔: https://nodejs.org/api/child_process.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.