ilinca18
ilinca18

Reputation: 51

Module "fs" has been externalized for browser compatibility. Cannot access "fs.createReadStream" in client code

I'm very new to react, and i'm trying to make an app that takes an image from folder and upon pressing a generate button creates an image variation with the help of DALL-E The url of the image is printed in the console. However, in the documentation from "openai" there is this function fs.createReadStream which React doesn't recognize. How could I replace this fs function with something else that reads an image from the folder?

    import { Configuration, OpenAIApi } from "openai";

    import fs from 'fs';
    import { useState } from "react";
    import "./App.css";

    function App() {
  
    const configuration = new Configuration({
    apiKey: import.meta.env.VITE_Open_AI_Key,
    });

    const openai = new OpenAIApi(configuration);

    const generateImage = async () => {
    const response = await openai.createImageVariation(
    fs.createReadStream("images/3.png"), 
    1,
    "1024x1024"
    );
    
    console.log(res.data.data[0].url);
    };
    return (
    <div>
      <button onClick={generateImage}>generate an image</button>
    </div>
    )  
    }

    export default App;

Upvotes: 5

Views: 2294

Answers (1)

The Profispojka
The Profispojka

Reputation: 41

If you want to upload a file through your React application, you can use <input type="file">, for more information, have a look there.

You cannot use the fs package, because it is not available in the browser enviroment. Javascript is a language that works both on frontend (inside a browser - on a machine under users control) and backend (inside a server - on a machine under your control). fs is a package, that is only available on the server and since React is a browser side library, you wont find it there.

Also please be aware, that calling open AI api is not meant to be done from the browser, because it comes with multiple issues - for example you are exposing your api keys there and since the code is accessible to the user, he can then exploit you api keys in a way you don't want to.

The correct way to setup you application is to setup both server side and client side apps. Create an endpoint on the server side app to "proxy" your request to openAI and call this endpoint from the client side React app.

To create your app with such endpoint, you could use the Express framework.

In order to deploy your server side app, you will need to setup a VPS and use some kind of proxy, like nginx.

Upvotes: 0

Related Questions