Can‘t import openai in Node

题意: 在 Node.js 环境中遇到无法导入(import)openai

问题背景:

I have Node 16.13.1 installed and I installed openai globally with 'npm install -g openai'. I imported the packages inside my script using

我已经安装了 Node 16.13.1,并且使用 'npm install -g openai' 命令全局安装了 openai。我在我的脚本中使用了以下方式导入了包。

python 复制代码
const { Configuration, OpenAIApi } = require('openai')

However, when I ran my script, I got this error:

然而,当我运行脚本时,得到了以下错误:

python 复制代码
PS D:\Projects\OpenAI-Chat> node conversation.js
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'openai'
Require stack:
- D:\Projects\OpenAI-Chat\conversation.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\Projects\OpenAI-Chat\conversation.js:1:38)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'D:\\Projects\\OpenAI-Chat\\conversation.js' ]
}

How do I fix this? 我怎样修复这个问题?

问题解决:

You have to install it locally with 你需要使用以下命令本地安装它

python 复制代码
npm i openai

because Node.js doesn't search in the global folder for dependencies for the local project. Global installation is for global executables and its dependencies.

因为 Node.js 不会在全局文件夹中搜索本地项目的依赖项。全局安装是用于全局可执行文件及其依赖项的。

相关推荐
2601_949847757 小时前
Flutter for OpenHarmony 剧本杀组队App实战:关于我们页面实现
开发语言·javascript·flutter
阿杰学AI7 小时前
AI核心知识69——大语言模型之SSM (简洁且通俗易懂版)
人工智能·ai·语言模型·自然语言处理·aigc·ssm·状态空间模型
weixin_422201307 小时前
Element Plus中el-tree组件默认选中第一个节点的实现方法
前端·javascript·vue.js
让我上个超影吧7 小时前
SpringAI会话记忆实现——基于MYSQL进行存储
java·spring boot·ai
css趣多多7 小时前
组件没有原生事件
前端·javascript·vue.js
IT陈图图7 小时前
Flutter × OpenHarmony 实战:优雅构建确认对话框的组件化方案
开发语言·javascript·flutter
雨季6667 小时前
Flutter 三端应用实战:OpenHarmony 简易文本末尾字符查看器开发指南
开发语言·javascript·flutter
布谷鸟科技cookoo7 小时前
布谷鸟科技携AI边缘计算产品线亮相韩国ROSCon KOREA 2026
人工智能·科技·ai·边缘计算·交通物流
渡我白衣7 小时前
从线性到非线性——神经网络的原理、训练与可解释性探索
开发语言·javascript·人工智能·深度学习·神经网络·机器学习·数字电路
夏沫mds7 小时前
Node.js 实现高保真 PDF 压缩:从 Canvas 方案到 Ghostscript 的踩坑实录
pdf·node.js