You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Node.js与cmd.exe的持续通信(不关闭进程)

How to Maintain Continuous Communication with cmd.exe in Node.js

The issue with your current code is the /c flag you’re passing to cmd.exe—this tells the command prompt to run the specified command and immediately exit afterward. To keep the process alive and send multiple commands over time, you need to spawn cmd without that flag, then use the child process’s stdin stream to write commands directly to it.

Here’s a revised example that keeps cmd.exe running and lets you send commands dynamically:

const { spawn } = require('child_process');

// Spawn cmd.exe without the /c flag to keep it running in interactive mode
// Note: Double backslashes are needed in JavaScript strings to escape the backslash character
const cmd = spawn('C:\\Windows\\System32\\cmd.exe');

// Listen for output from the command prompt's stdout
cmd.stdout.on('data', (data) => {
  console.log(`cmd output:\n${data}`);
});

// Listen for error messages from stderr
cmd.stderr.on('data', (data) => {
  console.error(`cmd error:\n${data}`);
});

// Log when the process exits (in case it does unexpectedly)
cmd.on('close', (code) => {
  console.log(`cmd process exited with code ${code}`);
});

// Example: Send a command after 1 second
setTimeout(() => {
  // Add a newline (\n) at the end to simulate pressing Enter
  cmd.stdin.write('echo Hello from Node.js!\n');
}, 1000);

// Send another command after 3 seconds
setTimeout(() => {
  cmd.stdin.write('dir\n');
}, 3000);

// To gracefully exit cmd later, uncomment this:
// setTimeout(() => {
//   cmd.stdin.write('exit\n');
// }, 5000);

Important Notes:

  • No /c flag: This keeps cmd.exe in interactive mode instead of executing a single command and terminating.
  • stdin.write(): Use this method to send commands to the cmd process. Always include a newline (\n) at the end of each command to simulate pressing the Enter key—otherwise, cmd won’t execute the command.
  • Output handling: The stdout event will capture all output from cmd, including prompts and command results. If you need to parse specific information from the output, you’ll need to process the raw data string accordingly.
  • Graceful shutdown: To close cmd.exe intentionally, send the exit\n command via stdin.write(), or use cmd.kill() if you need to force termination.

This approach lets you maintain a persistent connection with cmd.exe and send commands as needed without restarting the process each time.

内容的提问来源于stack exchange,提问作者thehorseisbrown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:21:34