javascript - 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.
解决方案
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);
});
};
推荐阅读
- python - 列表列表未正确分配值 Python
- opencv - 从复杂的 UI 中提取半结构化文本(高尔夫模拟器)
- javascript - React 不会在渲染中循环遍历状态
- spring-boot - Spring Boot Https 启动失败
- python - H2O DistributedRandomForest 所有树预测
- android - 使用对话框打开另一个应用程序 - 可以吗?
- javascript - JavaScript URL 正则表达式拆分
- java - 无法让 Java Hadoop 库在 Intellij 中工作
- sql - 在 Informix SQL 中将 3 个查询合二为一
- python - 对不同集群的特征进行分析和排序