导入图像

时间:2018-04-23 13:48:38

标签: node.js gm

我有以下脚本从api导入原始图像:

let importImages = function (meal,accessToken) {

  let imagesData = meal.afbeeldingenInfo;
  let mealFolder = 'client/import/meal-'+meal.maaltijdId;

  ensureExists(mealFolder, 0o755, function(err) {
    if (err) {
      winston.error('Not able to create a folder : %s', err.message);
    } else {
      winston.info('Folder %s succesfully created', mealFolder);
      for (let index in imagesData) {
        if (imagesData.hasOwnProperty(index)) {
          let imageData = imagesData[index];

          axios({
            method: 'get',
            responseType: 'stream',
            url: SYS_URL + '/MaaltijdAfbeelding/' + imageData.id,
            headers: {'Authorization': 'Bearer ' + accessToken},
          }).then(response => {
            winston.info('Got successful response from the API');
            // let image = response.data;
            let filePath = mealFolder + '/'+ imageData.name;
            response.data.pipe(fs.createWriteStream(filePath));
            winston.info('Image %s succesfully imported', imageData.name);
            response.data.on('end', () => {

              // generate images for all sizes
              for (var key in imageSizes) {
                if (imageSizes.hasOwnProperty(key)) {
                  let size = imageSizes[key];
                  gm(filePath).resize(size).strip().interlace('Line')
                    .write(mealFolder + '/' + key + '-' + imageData.name, function (err) {
                      if (!err) {
                        winston.info('Image %s successfully minimized to '+ size +'px', imageData.name)
                      } else {
                        winston.info('Not able to minimize image %s due to error: %s', imageData.name, err.message)
                      }
                    });
                }
              }
            })
          }).catch(error => {
            winston.error('Not able to import image %s due to error: %s', imageData.name, error.message);
          });
        }
      }
    }
  });
};

然而,当我执行此操作时,几秒钟后节点脚本完全冻结系统。

这不应该以这种方式完成吗?如果是这样,那么调整图像大小的更好方法是什么?

1 个答案:

答案 0 :(得分:1)

听起来你一次运行太多进程。我建议通过队列运行这些进程。

这意味着一次只能运行一个进程但是如果任何任务失败,您将能够在队列中重新处理它们。 This是一个很棒的运行队列库