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

相关推荐
@yanyu6669 分钟前
04vue3基础
前端·javascript·vue.js
恋喵大鲤鱼17 分钟前
OpenClaw 快速上手
ai
ofoxcoding22 分钟前
2026 大模型 API 价格一览:GPT-5/Claude 4.6/Gemini 3/DeepSeek V3 费率实测对比
gpt·ai
SuperEugene22 分钟前
Vue3 Props 传参实战规范:必传校验 + 默认值 + 类型标注,避开 undefined / 类型混用坑|Vue 组件与模板规范篇
前端·javascript·vue.js·前端框架
吴声子夜歌24 分钟前
JavaScript——数组
java·javascript·算法
weixin_4629019726 分钟前
ESP32电压显示
开发语言·javascript·css·python
一拳不是超人29 分钟前
2026年最值得关注的JavaScript新特性:Signals,响应式编程的下一个十年
前端·javascript·响应式编程
skiy29 分钟前
Webpack、Vite区别知多少?
前端·webpack·node.js
Luna-player33 分钟前
npm install vue-awesome-swiper@5.0.1 swiper@7.4.1安装后,我又想全删了,怎么移除
前端·vue.js·npm
belldeep35 分钟前
AI: 介绍 微软 BitNet 下载、安装、使用说明
人工智能·microsoft·ai·bitnet