carlos E.
carlos E.

Reputation: 115

Node.js SFTP ending connection

I am using a sh2-sftp-client module to do a sftp get request for multiple files. I can pull the files just fine but when I try to pull more then 10 files, I get an error: (node:4068) Warning: Possible EventEmitter memory leak detected. 11 ready listeners added. Use emitter.setMaxListeners() to increase limit and Error: (SSH) Channel open failure: open failed.

I was doing some searching and I was able to prevent the first this issue by increasing the EventEmitter: require('events').EventEmitter.defaultMaxListeners = 0;. I now this isn't the correct way to fix this because I need to close the connection after each request. But I am not sure where to add sftp.end.

route.js

    // Connect to server
    sftp.connect(config).then(() => {  
        //Grab file and set it as a readable stream
        sftp.get(fileName, "false", null).then((data) => {
            // This is what the file name will be
            res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
            // Setting headers to correct MIME type to the header of the response object
            res.setHeader('Content-Type', 'audio/wav');
            //Pipe the respose
            data.pipe(res);
            // End connection?
            sftp.end();
        });
    }).catch((err) => {
            console.log(err, 'catch error');
    }); 

Upvotes: 0

Views: 2237

Answers (1)

Bamse
Bamse

Reputation: 493

When there is no more data and since data is a read stream you can do this:

data.on('end', () => sftp.end())

Upvotes: 1

Related Questions