Axios posts the first part of the file and hangs

Viewed 19

I'm trying to send a file from my NodeJS Lambda function to Dailymotion, and I'm using the following code:

// Download the original file to the `tmp` folder of Lambda.
await axios.get('https://cdn.mysite.com/source.mp4', {
  responseType: 'stream'
})
.then( response => {
  response.data.pipe(fs.createWriteStream('/tmp/video.mp4'));
})
.catch(error => {
  console.log(error);
});

const form = new FormData();
form.append('file', fs.createReadStream('/tmp/video.mp4'));

// Post the file to Dailymotion API.
axios.post('https://upload-xx.xxx.dailymotion.com/upload?uuid=xxxxx&seal=xxxxx&extra=xxxxx', form, {
  headers: {
    ...form.getHeaders,
    'Content-Type': 'multipart/formdata',
    'Content-Length': fs.statSync('/tmp/video.mp4').size
  },
})
.then(response => {
  console.log(response);
})
.catch(error => {
  console.log(error);
});

I can use the following URL to check the upload progress of the file: https://upload-xx.xxx.dailymotion.com/progress?uuid=xxxxx, but it seems that it uploads only the first chunk of the file and then stops, and I'm not getting any error or response.

Did I miss anything here?

1 Answers

When you use await, the result in your case is not a promise but stream. So there's no sense in adding old-style .then and .catch to not-promise essense. Try the following.

try {
   const stream = await axios.get('https://cdn.mysite.com/source.mp4', {
      responseType: 'stream'
   });
   stream.pipe(fs.createWriteStream('/tmp/video.mp4'));
   stream.on('error', (err) => console.log({ err }));
   stream.on('close', async () => {
      try {
         const form = new FormData();
         form.append('file', fs.createReadStream('/tmp/video.mp4'));

         // Post the file to Dailymotion API.
         const postThis = await axios.post('https://upload-xx.xxx.dailymotion.com/upload?uuid=xxxxx&seal=xxxxx&extra=xxxxx', form, {
            headers: {
               ...form.getHeaders,
               'Content-Type': 'multipart/formdata',
               'Content-Length': fs.statSync('/tmp/video.mp4').size
            },
         });
         console.log({ postThis })
      } catch (err) { console.log({ err }) }

   })
} catch (err) { console.log({ err }) }
Related