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

Node.js v18.14.0中使用node-id3遇require未定义错误求助

解决node-id3包的require未定义错误

问题场景

通过npm i node-id3安装node-id3包后,在Node.js v18.14.0环境下执行文档示例代码:

const NodeID3 = require('node-id3')
NodeID3.read(file, function(err, tags) {})

触发以下错误:

const NodeID3 = require('node-id3')
                ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\root\Documents\GitHub\Database\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

解决方案

有两种可行的解决方式:

  • 改用ES模块import语法
    由于项目通过package.json中的"type": "module"配置为ES模块环境,直接替换require为import即可:

    import NodeID3 from 'node-id3'
    NodeID3.read(file, function(err, tags) {})
    
  • 将脚本转为CommonJS格式
    把当前的.js文件重命名为.cjs后缀,Node.js会自动将其识别为CommonJS模块,此时可以继续使用原有的require语法。

内容的提问来源于stack exchange,提问作者Alix Blaine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:22:40