如何将REST API返回数据传递至Node命令行并执行pkill命令?
pkill Command in copilotMonitor.js Got it, let's walk through how to make this work smoothly. The core idea is to capture the API's mode response directly in your copilotMonitor.js script, then use Node.js's built-in child_process module to run the pkill command with that dynamic value.
Step 1: Capture the API Response
First, make sure your copilotMonitor.js is correctly fetching the mode value from the REST API. Let's use node-fetch (install it via npm install node-fetch if you haven't already) for the API call, but you can swap this with axios or any HTTP client you prefer.
Step 2: Execute pkill with the Dynamic Mode Value
Use Node.js's child_process.execFile (safer than exec to avoid shell injection risks) to run the pkill command with the mode value from the API. Here's a complete, ready-to-use example:
const fetch = require('node-fetch'); const { execFile } = require('child_process'); // Function to check API and trigger process termination async function handleModeRestart() { try { // Replace with your actual API endpoint const apiRes = await fetch('https://your-api-endpoint.com/get-target-mode'); const targetMode = await apiRes.text(); // Assumes API returns plain text like "mode_3" // Add validation to avoid accidental process kills if (!targetMode.startsWith('mode_')) { console.warn(`Invalid mode received: ${targetMode} - skipping pkill execution`); return; } // Execute pkill with the validated mode value execFile('pkill', ['-9', '-f', targetMode], (error, stdout, stderr) => { if (error) { console.error(`Failed to run pkill: ${error.message}`); return; } if (stderr) { console.error(`pkill error output: ${stderr}`); return; } console.log(`Successfully terminated processes matching: ${targetMode}`); }); } catch (err) { console.error(`API call failed: ${err.message}`); } } // Trigger the function once on startup handleModeRestart(); // Optional: Set an interval if you need continuous monitoring (e.g., every 5 minutes) // setInterval(handleModeRestart, 5 * 60 * 1000);
Key Notes
- Security First:
execFileis preferred overexecbecause it passes arguments directly to the command without parsing them through a shell, eliminating shell injection risks. - Validation: The
startsWith('mode_')check ensures you only terminate processes matching your expected mode format—this prevents accidental kills of unrelated system processes. - Error Handling: Comprehensive error handling for both the API call and
pkillexecution makes debugging issues much easier.
Integrating with Your Existing Workflow
Since copilot.js starts copilotMonitor.js based on the --mode argument, this script will run alongside your main process and handle the restart logic automatically whenever the API returns a new mode value.
内容的提问来源于stack exchange,提问作者Jona Dev

