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.tsx679 chars28 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