Выполнение команд оболочки с помощью кнопки HTML в Node.js: методы и примеры

Чтобы выполнить команду оболочки с помощью кнопки HTML в среде Node.js, вы можете использовать следующие методы:

  1. Модуль дочерних процессов: Node.js предоставляет модуль child_process, который позволяет создавать дочерние процессы и управлять ими. Вы можете использовать функции execили execFileдля запуска команд оболочки. Вот пример использования exec:
const { exec } = require('child_process');
// Function to execute shell command
function executeShellCommand(command) {
  exec(command, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing command: ${error}`);
      return;
    }
    console.log(`Command output: ${stdout}`);
  });
}
// Express.js route handling POST request from button click
app.post('/execute-command', (req, res) => {
  const command = req.body.command; // Assuming command is sent in the request body
  executeShellCommand(command);
  res.send('Command executed successfully');
});
  1. Библиотека ShellJS: ShellJS — это переносимая реализация команд оболочки Unix для Node.js. Он позволяет запускать команды оболочки, используя знакомый синтаксис. Вы можете установить ShellJS с помощью npm и использовать его в своем проекте Node.js. Вот пример:
const shell = require('shelljs');
// Function to execute shell command
function executeShellCommand(command) {
  const result = shell.exec(command);
  if (result.code !== 0) {
    console.error(`Error executing command: ${result.stderr}`);
    return;
  }
  console.log(`Command output: ${result.stdout}`);
}
// Express.js route handling POST request from button click
app.post('/execute-command', (req, res) => {
  const command = req.body.command; // Assuming command is sent in the request body
  executeShellCommand(command);
  res.send('Command executed successfully');
});