download file axios nodejs

const axios = require('axios');
const fs = require('fs');

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

  const writer = fs.createWriteStream(outputPath);

  response.data.pipe(writer);

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

// Example Usage
const fileUrl = 'https://example.com/file.zip';
const outputFile = 'downloadedFile.zip';

downloadFile(fileUrl, outputFile)
  .then(() => console.log('File downloaded successfully'))
  .catch((error) => console.error('Error downloading file:', error));