Home > Enterprise >  Can't run terminal commands with exec
Can't run terminal commands with exec

Time:04-29

i'm trying to use exec function in nodejs, but it's not working.

Here is the code that i'm runing :

import { exec } from "child_process";

exec("ssh ubuntu@myserverip", (error, stdout, stderr) => {
    if (error) {
        console.error(`error: ${error.message}`);
    }

    if (stderr) {
        console.error(`stderr: ${stderr}`);
    }

    else {
        console.log(`stdout:\n${stdout}`);
    }
});

And that it what it returns :

terminal

While this is the output if I directly write on terminal :

terminal

Any idea about how can I fix it ?

CodePudding user response:

You should use spawn, exec is used to execute commands whose result is going to be delivered to me immediately, or in a very short time, it has to be fast and where the output or the result that is going to be delivered to me is not very large, because exec creates a Buffer (a memory space) where it will start storing all the output of the command, and besides that it has a timeout, and if the command does not finish in that time it kills the process.

  • Related