Skip to content

Error when executing command with streaming stdout/stderr callbacks #257

Closed

Description

@Ajay-MS

Sample code

ssh.connect(sshOptions).then(function() {

            Utils.formatLogs(hostname, "SSH comamnd : " + commandToExecute)


            ssh.exec(commandToExecute, {
                onStdout(chunk: any) {
                    console.log('stdoutChunk', chunk.toString('utf8'));
                },
                onStderr(chunk: any) {
                    console.log('stderrChunk', chunk.toString('utf8'));
                    throw chunk.toString('utf8');
                }
            });
        });

Error

TypeError: a.forEach is not a function
at shellescape (E:\GithubNew<user>\node_modules\shell-escape\shell-escape.js:7:5)

Activity

  1. steelbrain commented on Feb 6, 2020

    @steelbrain
    Owner

    Hi @Ajay-MS

    What's the value of commandToExecute here? You may want to use execCommand instead of exec here.

  2. steelbrain commented on Nov 16, 2026

    @steelbrain
    Owner

    Hi @Ajay-MS, sorry this sat for so long. The second argument of exec() is the list of parameters to escape, and options go third. Your snippet passed the options object as the parameters, which shell-escape then tried to iterate. Since v9, exec() checks its arguments, so this now rejects with AssertionError: parameters must be a valid array instead of a.forEach is not a function. Use either:

    await ssh.exec(command, [], { onStdout, onStderr })   // command plus escaped parameters
    await ssh.execCommand(command, { onStdout, onStderr }) // command is already a full string

    On the throw inside onStderr: in v14, if onStdout, onStderr or onChannel throws, the promise from exec/execCommand rejects with that error, and only that command's channel is closed. Before, the exception escaped into ssh2, which treated it as a connection error, closed the connection and crashed the process. If you only want to fail when the command writes to stderr, you don't need to throw. exec() with the default stream: 'stdout' already rejects with the stderr text, and execCommand() returns stderr and code for you to check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions