You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS项目中使用ImageMagick转换PDF时出现convert未定义错误

解决NestJS中ImageMagick调用convert时的Cannot read properties of undefined错误

我在为NestJS项目构建PDF转换服务时遇到错误:TypeError: Cannot read properties of undefined (reading 'convert')。我已经导入了ImageMagick,但调用im.convert()时抛出这个错误,相关代码如下:

import { InjectQueue, Process, Processor } from '@nestjs/bull';
import { Injectable, Logger } from '@nestjs/common';
import { Job, Queue } from 'bull';
import { pdfJob } from './pdfJob';
import im from 'imagemagick';
import { promises as fs } from 'fs';

@Injectable()
@Processor('pdf')
export class ImagemagickService {
  constructor(@InjectQueue('pdf') private readonly pdfQueue: Queue) {}

  private readonly logger = new Logger(ImagemagickService.name);

  @Process()
  async processPDF(job: Job<pdfJob>) {
    const IMAGE_DIR = `src/../config/img/`;
    const { pdfPath, baseName } = job.data;
    const outputPath = `${IMAGE_DIR}${baseName}.jpg`;

    this.logger.debug(`Converting ${job.data.pdfPath}`);

    try {
      // Promisify the callback of im.convert()
      const images = await new Promise((resolve, reject) => {
        // Take PDF file and generate individual JPG files
        im.convert(
          [
            '-alpha',
            'remove',
            '-density',
            300,
            '-quality',
            80,
            pdfPath,
            outputPath,
          ],
          async (err) => {
            if (err) {
              console.log(err);
              reject(err);
              throw `Couldn't Process ${pdfPath}`;
            } else {
              // Get every file in Temporary Image Directory
              let files = await fs.readdir(IMAGE_DIR);

              // Append directory into filenames
              files = files.map((file) => {
                return IMAGE_DIR + file;
              });

              // We only want the files that match the source pdf's name
              files = files.filter((file) => {
                return file.includes(baseName);
              });

              const output = { pdf: pdfPath, files };

              resolve(output);
            }
          },
        );

        return images;
      });
    } catch (e) {
      this.logger.error(e);
    }
  }
}

解决方案

1. 修正ImageMagick包的导入或更换包

当前使用的imagemagick包可能存在ES模块导出不兼容的问题,尝试改用CommonJS导入方式:

// 替换原导入语句
const im = require('imagemagick');

如果问题依旧,卸载现有包并重新安装:

npm uninstall imagemagick
npm install imagemagick

也可以考虑更换为更稳定的imagemagick-native包,安装后调整导入和调用逻辑。

2. 确认系统已安装ImageMagick CLI工具

Node的imagemagick包依赖系统级的ImageMagick工具,若系统未安装,包无法正常工作:

  • Windows:下载官方安装包并勾选"添加到系统PATH"选项
  • macOS:通过Homebrew安装 brew install imagemagick
  • Linux:使用包管理器安装,如Ubuntu执行 sudo apt-get install imagemagick

3. 修复代码中的逻辑错误

Promise构造函数内的return images;属于无效代码,会导致变量未定义的问题,直接删除这行。同时优化错误处理逻辑,避免在回调中重复抛出错误:

const images = await new Promise((resolve, reject) => {
  im.convert(
    [
      '-alpha', 'remove',
      '-density', 300,
      '-quality', 80,
      pdfPath,
      outputPath,
    ],
    async (err) => {
      if (err) {
        this.logger.error(`处理${pdfPath}失败`, err);
        reject(err);
        return;
      }
      let files = await fs.readdir(IMAGE_DIR);
      files = files.map(file => `${IMAGE_DIR}${file}`)
                   .filter(file => file.includes(baseName));
      resolve({ pdf: pdfPath, files });
    },
  );
});

内容的提问来源于stack exchange,提问作者Brandon Piña

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:54:37