NodeJS exif 返回未定义

问题描述 投票:0回答:1

我正在尝试从我的图像中获取 exif 信息。所以我做了一些划痕。它可以工作,但在循环中使用它时不起作用

嗨。我试图从我的图像中获取 exif 信息。所以我做了这个

const fs = require('fs');
const mime = require('mime');
const exif = require('exif-reader');
const ExifImage = require('exif').ExifImage;

function getFiles(dir, files = []) {
  const fileList = fs.readdirSync(dir);
  for (const file of fileList) {
    const name = `${dir}/${file}`;
    if (fs.statSync(name).isDirectory()) {
      getFiles(name, files);
    } else {
      files.push(name);
    }
  }
  return files;
}

function getEXIF(filepath){
    try {
        new ExifImage({ image : filepath }, function (error, exifData) {
            if (error)
                console.log('Error: '+error.message);
            else
                console.log(exifData.image); 
        });
    } catch (error) {
        console.log('Error: ' + error.message);
    }
}


//getEXIF('D://MyTestImage.jpg')


const filearr=getFiles('D://Photoes', files = [])
filearr.forEach((element) => {
     const ftype=mime.getType(element)
     if (ftype=='image/jpeg'){
         console.log(getEXIF(element))
     }
 }
 );

当我对一个特定文件运行 getEXIF 函数时,它工作正常。但是当我尝试在 foreach 循环中使用它时,它返回未定义。为什么?。我确信该元素包含文件路径,因为它非常适合 mime.getType 函数并返回一个值。

请指出我的错误。

node.js exif
1个回答
1
投票

首先,您需要重构

getEXIF()
以返回 exif 数据。由于您没有返回任何东西,因此您会得到
undefined

其次,

ExifImage
接受回调,该回调提供
exifData
作为第二个参数。

function (error, exifData) {}

从回调中获取

exifData
并使用它从
getEXIF
进行响应的最简单方法是使用 Promise

我们将 getEXIF 包装在一个 Promise 中,然后使用

ExifImage
reject
resolve
回调中进行响应。

async function getEXIF(filepath) {
   return new Promise((resolve, reject) => {
       try {
           new ExifImage({ image : filepath }, function (error, exifData) {
               if (error)
                   reject(error);
               else
                   resolve(exifData.image); 
           });
       } catch (error) {
           reject(error);
       }
   });
}

然后您可以将其用作:

const exif = await getEXIF('D://MyTestImage.jpg');
console.log(exif)
© www.soinside.com 2019 - 2024. All rights reserved.