0

I am trying to load multiple files from ftp but I am getting error: "write after end". I am not able to find the issue.

connections.js

async function getFtpFileContent(_path) {
  const ftpConfig = {
    host: config.FTPhost.replace('https://', ''),
    username: config.FTPusername,
    password: config.FTPpassword
  };
  let ftpFileContent;
  let sftp = new StfpClient();
  try {
    await sftp.connect(ftpConfig);
    const stream = await sftp.get(_path);
    ftpFileContent = await readStream(sftp, stream);
    stream.close();
    await sftp.end();
  } catch (error) {
    console.log('FTP Error: \n', error);
  }

  return ftpFileContent;
}


function readStream(sftp, stream) {
  return new Promise((resolve, reject) => {
    let body;
    stream.on('data', chunk => {
      body += chunk;
    });
    stream.on('end', () => {
      resolve(body);
    });
    stream.on('error', err => reject(err));
  });
}

calling in the next method:

async function getFiles(req, res) {
  // first file
  let fileContent = await conn.getFtpFileContent(filePath);

  // second file
  let fileContent2 = await conn.getFtpFileContent(filePath2);
}

When I call the method getFtpFileContent second time I got the mentioned error ("write after end").

Could you please help me? Where I doing the mistake?

tumik
  • 1

2 Answers2

0

I'm not sure where your problem is but should you be calling stream.close() in the getFtpFileContent function? I don't see anything about a close method for a stream, only a close event.

T. Stoddard
  • 111
  • 4
  • I am not sure if I understand correctly ... This `const stream = await sftp.get(_path);` return ReadableStream. How I should close it? I tried `stream.destory()` and `stream.close()` and still same result. – tumik Jan 28 '19 at 09:20
  • I'm not sure that you need to close it. Perhaps that's what's causing the error that you're seeing. – T. Stoddard Jan 28 '19 at 12:02
0

I found the issue. The issue was in CSV converter which I used later. The converter used writable stream which was not close after convert.

tumik
  • 1