node js request download file

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

const fileUrl = 'URL_OF_YOUR_FILE';
const outputFilePath = 'PATH_TO_SAVE_DOWNLOADED_FILE';

const download = (url, dest, callback) => {
  const file = fs.createWriteStream(dest);
  const sendReq = request.get(url);

  sendReq.on('response', (response) => {
    if (response.statusCode !== 200) {
      return callback(`Response status was ${response.statusCode}`);
    }

    sendReq.pipe(file);

    file.on('finish', () => {
      file.close(callback(null, dest));
    });

    file.on('error', (err) => {
      fs.unlink(dest);
      return callback(err.message);
    });
  });

  sendReq.on('error', (err) => {
    fs.unlink(dest);
    return callback(err.message);
  });

  file.on('error', (err) => {
    fs.unlink(dest);
    return callback(err.message);
  });
};

download(fileUrl, outputFilePath, (err, filePath) => {
  if (err) {
    console.error(err);
    // Handle error
  } else {
    console.log(`File downloaded to ${filePath}`);
    // File download successful, do something with the file
  }
});

This Node.js code uses the 'fs' and 'request' modules to download a file from a given URL. It creates a writable stream using 'fs.createWriteStream' to save the downloaded file. The 'request.get' method initiates the download and handles the response.

The 'response' event checks if the response status is 200 (OK). If it is, it pipes the data received from the request to the writable stream created earlier. It listens for the 'finish' event on the writable stream, which indicates that the file download is complete. In case of any errors during the download, it handles them by removing the partially downloaded file ('fs.unlink') and calling the callback function with an error message.

The 'error' event on both the request and the file stream handles errors related to the request or the file stream itself. The 'download' function takes in the URL of the file, the path where the file should be saved, and a callback function that handles errors or provides the downloaded file's path upon successful download.