Programmatically Analyzing a Text File Using the OpenAI API with JavaScript

A few days ago, I put together a short demo of programmatically analyzing a text file using the ChatGPT API with Python. I figured I’d refactor that Python program to JavaScript. Conceptually, refactoring from Python to JavaScript is simple, but as expected, there were a lot of details to handle.

In a nutshell, the demo reads the contents of the source text file, and then passes that content as a preliminary message, and then follows up with a query about the file content. The tricky part is that reading the contents of a file using JavaScript requires a callback function.

While I was searching for examples on the Internet, I noticed that because AI development is so fast, the majority of examples I found were completely out of date and most didn’t even run.

Well, after about three hours I had a demo up and running. There are still several things about my demo that I don’t have a full understanding of, but, every program has to start with getting something running.

I have an existing OpenAI account and a couple of existing keys for use in programs that call the API. I created a text file document using the first couple of pages of the Wikipedia entry on the planet Venus. (I copy-pasted the text into Notepad and then saved it as venus.txt).

Here’s an output of one run of my demo:

C:\JavaScript\ChatGPT\QueryTextFile: node text_files_chatgpt.js

Begin ChatGPT text file with JavaScript demo

Reading file ./venus.txt

Done

The question is:
What is an interesting fact about Venus?

The answer is:
Certainly! Here is an interesting fact about Venus based
on your text:

**Venus has a day that is longer than its year.**
Because Venus rotates very slowly on its axis, a single
day (one complete rotation) on Venus lasts about 116.75
Earth days. In contrast, it takes 224.7 Earth days for
Venus to complete one orbit around the Sun (a Venusian
“year”). So, a day on Venus is more than half as long
as a Venus year!

Another fun fact: Venus rotates in the opposite direction
of most planets, including Earth—this is called
**retrograde rotation**.

C:\JavaScript\ChatGPT\QueryTextFile:

The program is short but a bit tricky, so I won’t try to explain it. Briefly, most of the code is inside an async processData(fileData) method because of the strange way that node.js reads a text file. But the program is really best understood by carefully examining the code.

I wanted to make sure that the query-PDF-file program was correctly pulling information from the PDF file, rather than using the GPT built-in knowledge of Venus that it learned during training (GPT uses the text of Wikipedia for training). I modified the source PDF file to include the fake sentence, “A little-known fact is that the surface of Venus is pink, not green.” And then a paragraph later I added a fake sentence, “Because Venus soil is pink, Venus is sometimes called the cotton candy planet.” When I reran the query program, the response was:

The answer is:
An interesting fact about Venus is that a little-known
claim is that the surface of Venus is pink, not green.
This is mentioned in your text:

"A little-known fact is that the surface of Venus is pink,
not green."

Additionally, Venus is sometimes called the "cotton candy
planet" because of this pink soil.

However, it's important to note that most scientific
sources describe the surface of Venus as having a
basalt-like dark gray color, possibly oxidized red,
and that

So, indeed, the program was pulling from the source PDF document. Very nice.

My demo extracts text from a file and then feeds that text to respnses.create() as context via input/content, and then sends a query which knows about the context. An important alternative is to create an OpenAI vector store database, upload the text file to the vector store, and then use the file_search tool parameter in responses.create() to query the file contents. But that’s an exploration for another day.

One takeaway is that AI via ChatGPT, Claude, and the others, are developing with blistering speed, which means that the Internet is littered with out-of-date and irrelevant examples (maybe even this one by the time you’re reading it.)



Because the OpenAI API is evolving so quickly, if you use the API it’s important to keep your eyes on it to monitor the changes.

I’m a big fan of old science fiction movies. For some reason, posters that emphasize eyes are especially memorable to me.

Left: “The Brain Eaters” (1958) has a great poster. Sadly, the movie itself is not so great. A strange metallic cone appears in the woods outside a small town. And then people start acting strangely. The cone has parasites that latch onto people’s necks and control them (just like “The Puppet Masters” — one of the best sci fi novels of all time). The parasites are defeated in the end via electricity. I give this movie a C grade.

Center: In “Queen of Blood” (1966), a crew from Earth travels to Mars to rescue an alien spacecraft that has called for help. The crashed alien ship has only one occupant — a green-skinned woman who turns out to be a space vampire. The alien vampire woman is killed in the end but she leaves behind a lot of eggs. I give this movie a B- grade.

Right: In “Journey to the Seventh Planet” (1962), a crew from Earth travels to Uranus. The planet hosts a brain creature that takes control of some of the crew, with the plan to travel to Earth and conquer it. Most of the crew escape and get back to Earth. My grade: C.


Demo program:

// text_files_chatgpt.js
// query a text file

// node.js v22.16.0
// npm install openai

import fs from "fs";
import OpenAI from "openai";  // npm install openai

console.log("\nBegin ChatGPT text file with JavaScript demo ");

const fp = "./venus.txt";
console.log("\nReading file " + fp.toString());

// ----------------------------------------------------------

fs.readFile(fp, "utf-8", (err, fileData) => {
  if (err) {
    console.log(err);
    return;
  }
  processData(fileData);
});

// ----------------------------------------------------------

async function processData(fileData)
{
  //console.log(fileData);  // from readFile()
  const key = "sk-proj-_AX7bGTXUwg-qojh2T5Z2CVXrox" +
  "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
  "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +
  "_TbyJ6Pu3Ex8FqgDOFFjKPpbZ3HsmyLwIcOsIldlZd7npEA";

  const oai = new OpenAI({apiKey: key})

  const question = "What is an interesting fact about Venus?";
  console.log("\nThe question is: ");
  console.log(question);
  
  const response = await oai.responses.create({
    model: "gpt-4.1",
    input: [
      {
        role: "developer",  // aka system
        content: "You analyze a text file",
      },
      {
        role: "user",
        content: fileData,
      },
      { 
        role: "user",
        content: question,
      },
    ],
    temperature: 0.2,  // not creative
    top_p: 1.0,  // default max explore
    max_output_tokens: 100,
  });

  console.log("\nThe answer is: ");
  console.log(response.output_text);
}

console.log("\nDone ");
This entry was posted in OpenAI. Bookmark the permalink.

Leave a Reply