node js file dowload progress bar

const https = require('https');
const fs = require('fs');
const { createWriteStream } = require('fs');
const { statSync } = require('fs');
const { once } = require('events');

const downloadFile = (url, destination) => {
  return new Promise(async (resolve, reject) => {
    const file = createWriteStream(destination);
    const request = https.get(url, (response) => {
      const totalSize = parseInt(response.headers['content-length'], 10);
      let downloadedSize = 0;

      response.on('data', (chunk) => {
        downloadedSize += chunk.length;
        const percent = ((downloadedSize / totalSize) * 100).toFixed(2);
        process.stdout.clearLine();
        process.stdout.cursorTo(0);
        process.stdout.write(`Downloading... ${percent}%`);
        file.write(chunk);

        if (downloadedSize === totalSize) {
          process.stdout.write('\n');
          file.end();
          resolve(destination);
        }
      });

      response.on('end', () => {
        resolve(destination);
      });

      response.on('error', (error) => {
        reject(error);
      });
    });

    request.on('error', (error) => {
      reject(error);
    });

    const [event] = await once(file, 'open');
    if (event === 'open') {
      const fileSize = statSync(destination).size;
      const percent = ((fileSize / totalSize) * 100).toFixed(2);
      process.stdout.write(`Resuming download... ${percent}%`);
    }
  });
};

// Example usage:
const fileUrl = 'https://example.com/sample.zip';
const destinationPath = 'sample.zip';

downloadFile(fileUrl, destinationPath)
  .then((filePath) => {
    console.log(`File downloaded successfully: ${filePath}`);
  })
  .catch((error) => {
    console.error(`Error downloading file: ${error.message}`);
  });