user13841165
user13841165

Reputation:

Can't import openai in Node

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:

const { Configuration, OpenAIApi } = require('openai')

However, when I ran my script, I got this error:

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?

Upvotes: 1

Views: 10783

Answers (2)

Albert Renshaw
Albert Renshaw

Reputation: 17902

You can install it globally with

npm i -g openai


And then simply export to your node path so that global packages can be used anywhere without needing their local installation.

For mac:

export NODE_PATH=$(npm root -g)

For windows:

set NODE_PATH=%AppData%\npm\node_modules


Now you can simply use it anywhere in nodeJS using:

const OpenAI = require('openai');
const openai = new OpenAI();

Upvotes: 1

jabaa
jabaa

Reputation: 6840

You have to install it locally with

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.

Upvotes: 7

Related Questions