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

相关推荐
好奇的菜鸟3 小时前
掌握 npm 核心操作:从安装到管理依赖的完整指南
前端·npm·node.js
STUPID MAN4 小时前
arcgis js统计FeatureLayer的椭球面积、平面面积
javascript·arcgis·椭球面积·平面面积
Hellyc4 小时前
springAI调用deepseek模型使用硅基流动api的配置信息
spring·ai
杰瑞学AI4 小时前
深度学习中的分布偏移问题及其解决方法
人工智能·深度学习·机器学习·ai
JAVA学习通5 小时前
JavaScript网页开发设计(轮播图)
javascript
在未来等你5 小时前
互联网大厂Java求职面试:云原生架构与AI应用集成解决方案
java·spring cloud·微服务·ai·云原生·kubernetes·大模型
黛琳ghz5 小时前
CodeBuddy(腾讯云代码助手)最新功能——智能体 Craft 体验
人工智能·vscode·ai·腾讯云·codebuddy·腾讯云代码助手·craft
会飞的鱼先生5 小时前
vue3自定义指令来实现 v-copy 功能
前端·javascript·vue.js
谢尔登7 小时前
【React Native】快速入门
javascript·react native·react.js
进取星辰7 小时前
32、跨平台咒语—— React Native初探
javascript·react native·react.js