[英]Using node.js and wget, wait for the download to end
我正在使用wget下載一些圖像,但是有時圖像不能完全下載(它從頂部開始,然后突然停止...)這是我的代碼:
try {
var img = fs.readFileSync(pathFile);
}
catch (err) {
// Download image
console.log('download')
wget({
url: reqUrl,
dest: pathFile,
timeout : 100000
}, function (error, response, body) {
if (error) {
console.log('--- error:');
console.log(error); // error encountered
} else {
console.log('--- headers:');
console.log(response); // response headers
console.log('--- body:');
//console.log(body); // content of package
var img = fs.readFileSync(pathFile);
等等...
基本上,它會嘗試查找位於pathFile的文件,如果他不存在,我將使用wget將其下載到服務器上。 但是似乎wget在完成下載之前啟動了回調...
謝謝!
似乎您可能正在響應某些請求,但是您正在使用阻止函數調用(在它們的名稱中帶有“ Sync”的調用)。 我不確定您是否意識到了這一點,但這會在整個操作過程中阻塞您的整個流程,並且如果您需要的話,它將完全破壞並發的任何機會。
今天,您可以在看起來已同步但完全不阻塞代碼的Node中使用async
/ await
。 例如,使用request-promise
和mz
模塊,可以使用:
const request = require('request-promise');
const fs = require('mz/fs');
現在您可以使用:
var img = await fs.readFile(pathFile);
這不會阻塞,但仍然可以讓您輕松地等待文件加載,然后再運行下一條指令。
請記住,您需要在使用async
關鍵字聲明的函數中使用它,例如:
(async () => {
// you can use await here
})();
您可以通過以下方式獲取文件:
const contents = await request(reqUrl);
你可以這樣寫:
await fs.writeFile(name, data);
無需為此使用阻塞調用。
您甚至可以使用try
/ catch
:
let img;
try {
img = await fs.readFile(pathFile);
} catch (e) {
img = await request(reqUrl);
await fs.writeFile(pathFile, img);
}
// do something with the file contents in img
甚至有人可能會爭辯說,您可以刪除最后一個await
但是您可以將其保留,以等待潛在的錯誤出現(作為對承諾的拒絕的例外)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.