M Miller
M Miller

Reputation: 5662

Catching ECONNRESET error from spawned Node process

I am using the sftps NPM to connect to a SFTP server using username/password authentication and upload a file. This works beautifully when successful; however, if provided invalid authentication information, after several minutes it emits an ECONNRESET error which crashes my entire application.

Looking at the source of the sftps module, it appears to use child_process.spawn to run the shell commands, and looks like it should be capturing any errors gracefully:

var sftp = spawn(shellCmd, shellOpts);

var data = "";
var error = "";

sftp.stdout.on('data', function (res) {
    data += res;
});

sftp.stderr.on('data', function (res) {
    error += res;
});

function finished(err) {
    error = error.split('\n').filter(function(line) {
        if (/^Connected to /.test(line)) return false;
        return true;
    }).join('\n');
    data = data.split('\n').filter(function(line) {
        if (/^sftp> /.test(line)) return false;
        return true;
    }).join('\n');
    if (callback) {
        if (err) {
            callback(err, { error: error || null, data: data });
        } else if (error) {
            callback(null, { error: error, data: data });
        } else {
            callback(null, { error: null, data: data });
        }
        callback = null;
    }
}

sftp.on('error', finished);

sftp.on('exit', function (code) {
    if (code === 0) {
        finished();
    } else {
        finished('Nonzero exit code: ' + code);
    }
});
sftp.stdin.write(cmdString, 'utf8');

It looks like it has hooked into the stderr stream as well as capturing the error and exit events on the sub-process.

What else can I do to capture this ECONNRESET error and log it without killing the application?

Upvotes: 0

Views: 931

Answers (1)

user440788
user440788

Reputation:

Don't know if you're having the same problem that I was having, but I eventually solved it by attaching an event to stdin.on("error"). You could try this to see if that's the problem:

sftp.stdin.on("error", function (e)
{
    console.log("STDIN ON ERROR");
    console.log(e);
});

Upvotes: 2

Related Questions