ubuntu – Unable to stop and start node-red using ssh2

I have node-red on ubuntu, my install directory has the settings file in this path /usr/local/lib/node_modules/node-red/settings.js

I am trying to start/stop the service using ssh2:

    async function stopNodeRed(sshClient) {
  try {
    await executeCommand(sshClient, "sudo systemctl stop nodered");
    console.log("Node-RED stopped successfully.");
  } catch (err) {
    if (err.message.includes("failed with code 1")) {
      console.warn("Node-RED is already stopped or failed to stop.");
    } else {
      throw err;
    }
  }  
}

async function startNodeRed(sshClient) {
  try {
    await executeCommand(sshClient, "sudo systemctl start nodered");
    console.log("Node-RED started successfully.");
  } catch (err) {
    throw new Error("Failed to start Node-RED");
  }
}

function executeCommand(sshClient, command, options = {}) {
  return new Promise((resolve, reject) => {
    sshClient.exec(command, (err, stream) => {
      if (err) {
        console.error("Error executeCommand 1:", err);
        reject(err);
        return;
      }

      let stdout = "";
      let stderr = "";

      stream.on("data", (data) => {
        stdout += data.toString();
      });

      stream.stderr.on("data", (data) => {
        stderr += data.toString();
      });

      stream.on("close", (code, signal) => {
        if (code === 0) {
          resolve({ stdout, stderr });
        } else {
          console.error(
            "Error executeCommand 2:",
            `Command '${command}' failed with code ${code}`
          );
          reject(new Error(`Command '${command}' failed with code ${code}`));
        }
      });
    });
  });
}

but it is giving me error: 
Error executeCommand 2: Command 'sudo systemctl stop nodered' failed with code 1

Node-RED is already stopped or failed to stop.

Read more here: Source link