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

相关推荐
天平1 天前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
山河木马1 天前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林8181 天前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
垚森1 天前
AI时代,让曾经的遗憾变成现实
ai
AlbertZein1 天前
Agent任务实测:谁能稳定跑完,谁只是看起来很强?
aigc·openai·ai编程
leonshi1 天前
使用embedchain快速建立rag知识库,本地大模型
ai·rag·ollama
kyriewen1 天前
别再每次都 Google 了:我整理了前端日常最常踩的 10 个 Git 坑,附速查表
前端·javascript·git
AlbertZein1 天前
别被模型宣传骗了,真实 Agent 任务一跑就知道
aigc·openai·ai编程
SmartBoyW1 天前
深入ECMAScript规范:彻底搞懂JS隐式类型转换与底层ToPrimitive机制
前端·javascript
用户852495071841 天前
解密 JavaScript 中的 this:谁才是真正的调用者?
javascript·面试