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

相关推荐
天天扭码21 分钟前
在项目中常见的main.js和main.mjs有什么区别,我们该如何选择?
前端·javascript·面试
AI蜗牛车1 小时前
【LLM+Code】Windsurf Agent 模式Prompt&Tools详细解读
ai·大模型·llm·agent
三巧1 小时前
纯CSS吃豆人(JS仅控制进度)
javascript·css·html
软件技术NINI2 小时前
html css js网页制作成品——HTML+CSS+js美甲店网页设计(5页)附源码
javascript·css·html
天天扭码2 小时前
从数组到对象:JavaScript 遍历语法全解析(ES5 到 ES6 + 超详细指南)
前端·javascript·面试
拉不动的猪2 小时前
前端开发中常见的数据结构优化问题
前端·javascript·面试
chegan2 小时前
用c#从头写一个AI agent,实现企业内部自然语言数据统计分析(二)-数据结构和代码分析方法
ai·c#·agent
天天扭码3 小时前
ES6 Symbol 超详细教程:为什么它是避免对象属性冲突的终极方案?
前端·javascript·面试
小矮马3 小时前
React-组件和props
前端·javascript·react.js
泯泷3 小时前
探索DeepWiki:开发者的代码知识库利器
github·openai·ai编程