'How to make sure ftp stream is fully download?

This is my code

const execute = async() => {
  const dir = `c://users/xxx/desktop/test/`
  const ftp = new PromiseFtp()
  try {
    await ftp.connect(config)
    for (let word of word_name) {
      let lists = await ftp.list(`/loc/${word}/`)
      let file = lists.slice(-2)[0] //get recent file
      let file_path = `${dir}${file.name}`
      const stream = await ftp.get(`/loc/${word}/${file.name}`)
      await new Promise((resolve, reject) => {
        stream.once('end', resolve)
        stream.once('error', reject)
        stream.pipe(fs.createWriteStream(file_path))
      })
      let byte = fs.readFileSync(file_path )
      byte = iconv.decode(byte, 'big5')
      console.log(byte)
    }
  } catch(e) {
    console.error(e)
  } finally {
    return ftp.end()
  }
}

I use promise-ftp module, sometimes the byte in the loop all return correct value,but sometimes one or more than one value just return undefined,I think the reason is asynchronous stream, I tried use stream.once('finish')and other way,but it not working too,anyone can explain why? thanks。



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source