首页 > 解决方案 > Node Requests - Would like to return path/file name once complete? Or any best practice suggestions

问题描述

I'm trying to download a file async. I'm able to do that using Promises. I'm trying to figure out how to return the file patch back once it's completed. I had a hell of a time trying to figure out how to make this thing wait until the file has been written to disk.

If there is a better way, without using call backs I would love any suggestions.

Here's my function.

async function downloadFile(urlToFile, filename) {
  return new Promise( resolve => {
    const download = request({ url: urlToFile, followAllRedirects: true }).pipe(fs.createWriteStream(filename).on('finish', resolve));
  });
};

I call it with await in another file.

标签: javascriptnode.jses6-promise

解决方案


Event finish of writable streams actually doesn't mean everything finishes. It only indicates that the process of writing data to the related file completes. At that time, file descriptor is still opening and the file is not yet ready to use. If you want to check if everything is really done, you will need to use event close instead.

async function downloadFile(urlToFile, filename) {
  return new Promise( (resolve, reject) => {
    const fstream = fs.createWriteStream(filename);
    fstream.on('close', resolve);
    fstream.on('error', reject);
    const download = request({ url: urlToFile, followAllRedirects: true }).pipe(fstream);
  });
};

推荐阅读