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 不会在全局文件夹中搜索本地项目的依赖项。全局安装是用于全局可执行文件及其依赖项的。

相关推荐
七牛开发者19 分钟前
拆解 dsh:Session 的事件溯源与状态重建
javascript·github·agent
lifallen20 分钟前
长任务怎样选择遗忘:clearing、compaction 与 memory
人工智能·学习·ai·ai编程
Luhui Dev22 分钟前
大角几何如何保证图片导出尺寸一致性?
人工智能·数学·ai·luhuidev
梨想橙汁23 分钟前
JS BOM 浏览器对象:定时器与同步异步底层理解
前端·javascript
云烟成雨TD27 分钟前
LlamaIndex 系列【14】数据接入流水线(IngestionPipeline)
ai·agent·rag·llamaindex
梨想橙汁29 分钟前
ES6+ 必用新特性:箭头函数、解构、模板字符串、扩展运算符
前端·javascript
梨想橙汁31 分钟前
DOM 与 JS 事件:页面元素操作、事件冒泡、事件委托实战
前端·javascript
一个游离的指针1 小时前
浏览器的渲染原理
前端·javascript
俊哥V1 小时前
AI一周事件 · 2026-08-26 至 2026-09-01
人工智能·ai
ynchyong2 小时前
JavaScript Promise 实战:.then() 与 .catch() 的区别及回调函数封装指南
开发语言·javascript·ecmascript·promise·then