G
G
Gleb Kiselev2020-02-14 10:42:22
Node.js
Gleb Kiselev, 2020-02-14 10:42:22

How to organize the download of an audio file as a stream from telegram in express.js using axios?

I have a handler (middleware) that receives the ID of an audio file from telegram as input.

router.get('/api/track/:id', async(req, res) => {
  // Создаем бота использую плагин Telegraf с прокси агентом
  const telegram = new Telegram(token, { agent });
  const fileId = req.params.id;

  let url; // Сюда запишем ссылку
  try {
    url = await telegram.getFileLink(fileId); // Получаем ссылку на файл
  } catch (error) {
    console.log(error);
  }

// ...
}


Next, I want to start downloading this file from the link as a stream and send this stream to the client (spa) part.

res.set('content-type', 'audio/mp3');
res.set('accept-ranges', 'bytes');

  try {
    let audioFile = await axios({
      url, // Ссылка на файл в телеграме
      method: 'GET',
      responseType: 'stream'
    })

    audioFile.data.pipe(res)

    audioFile.on('error', err => {
      res.statusCode = 500
      res.end("Server Error")
      console.error(err)
    });

    audioFile
      .on('open', (chunk) => {
          console.log("open")
         res.write(chunk)
      })
      .on('close', () => {
          console.log("close")
          res.end()
      })

    res.on('close', () => {
      audioFile.destroy();
    })

  } catch (error) {
    console.log(error)
  }


And I catch an error: read ECONNRESET at TLSWrap.onStreamRead (internal/stream_base_commons.js:111:27

For telegram, I use a proxy and it works.
What's the problem, where did I make a mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gleb Kiselev, 2020-02-18
@Glebkiselev11

I found the problem, it turned out that I completely forgot about the fact that you also need to attach a proxy to the axios, since it downloads the file from the telegram ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question