Javascript 使用node.js和wget,等待下载结束

Javascript 使用node.js和wget,等待下载结束,javascript,node.js,wget,Javascript,Node.js,Wget,我正在使用wget下载一些图像,但有时图像不会完全下载(它从顶部开始,然后突然停止…) 这是我的密码: try { var img = fs.readFileSync(pathFile); } catch (err) { // Download image console.log('download') wget({ url: reqUrl, dest: pathFile, timeout : 100000 }, function (error, re

我正在使用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”的函数调用)。我不确定您是否意识到了这一点,但这会在操作期间阻塞整个进程,并且如果您需要,会完全破坏任何并发的机会

现在,您可以在看起来同步但根本不阻塞代码的节点中使用
async
/
wait
。例如,使用
request promise
mz
模块,您可以使用:

const request = require('request-promise');
const fs = require('mz/fs');
var img = await fs.readFile(pathFile);
现在您可以使用:

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

甚至有人会争辩说,您可以删除最后一个
wait
,但您可以让它等待潜在错误作为承诺拒绝的例外情况出现。

那么,我可以替换每个var img=fs.readFileSync(pathFile);by(async()=>{var img=await fs.readFileSync(pathFile);})();还是需要将整个函数放在异步函数中?