使用NestJS集成ytdl-core调用getInfo时出现未定义错误求助
解决ytdl-core调用getInfo时的"Cannot read properties of undefined"错误
问题分析
错误TypeError: Cannot read properties of undefined (reading 'getInfo')说明你导入的ytdl变量为undefined,无法访问其getInfo方法。核心原因是ytdl-core的导入方式与当前项目的模块系统不匹配。
解决方案
1. 确认依赖已正确安装
先确保ytdl-core已经安装到项目中:
npm install ytdl-core # 或使用yarn yarn add ytdl-core
2. 修改导入方式
ytdl-core属于CommonJS模块,在TypeScript/NestJS环境下,默认导入无法正确获取模块导出,需改为命名空间导入:
import { Injectable } from '@nestjs/common'; import { CreateDawnloadDto } from './dto/create-dawnload.dto'; import * as ytdl from 'ytdl-core'; // 调整为该导入方式 import fs from 'node:fs'; @Injectable() export class DawnloadService { async create(createDawnloadDto: CreateDawnloadDto) { // getInfo是异步方法,需添加await获取实际结果 const videoInfo = await ytdl.getInfo("https://www.youtube.com/watch?v=har3c93pJe0"); console.log(videoInfo); return createDawnloadDto.videoURL } }
额外提示
- 若项目启用了ES模块配置(
package.json中type: "module"),可尝试导入ES模块版本的ytdl-core:import ytdl from 'ytdl-core/esm.js' - 务必给
getInfo添加await,否则只会返回Promise对象,无法拿到实际视频信息
内容的提问来源于stack exchange,提问作者iago Bomfim
相关产品推荐
相关产品推荐

