download a zip file to tmp using axios in javascript

To download a zip file using Axios in JavaScript and save it to the system's temporary directory (tmp), you can use the following code:

index.tsx
const axios = require('axios');
const fs = require('fs');
const os = require('os');
const path = require('path');

const downloadZip = async (url) => {
  const response = await axios({
    url,
    method: 'GET',
    responseType: 'stream',
  });

  const tmpDir = os.tmpdir();
  const tmpFilePath = path.join(tmpDir, 'file.zip');

  const writer = fs.createWriteStream(tmpFilePath);
  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on('finish', resolve);
    writer.on('error', reject);
  });
};

// Usage example
const zipUrl = 'https://example.com/file.zip';
downloadZip(zipUrl).then(() => console.log('Zip file saved to tmp directory'));
679 chars
28 lines

In this code, we first import the required Node.js modules: axios, fs, os, and path.

We then define a function downloadZip that takes url as input, which is the URL of the zip file to be downloaded. Inside this function, we first execute an Axios GET request by setting method to 'GET' and responseType to 'stream'. This allows us to directly stream the file to the output file stream.

Next, we set the tmpDir variable to the path of the system's temporary directory using os.tmpdir(), and set tmpFilePath variable to the path of the output file in the temporary directory using path.join().

We then create a write stream using fs.createWriteStream() with the tmpFilePath, and pipe the data from the Axios response stream to the write stream using response.data.pipe(writer).

Finally, we return a Promise that resolves when the writer stream finishes writing and rejects on error.

To use this function, you can pass the URL of the zip file that you want to download as an argument to downloadZip(). When the function finishes executing, the zip file will be saved in your system's temporary directory, and you can use the file for further processing.

gistlibby LogSnag