skip to Main Content

I’m creating a Wordle-like game and I need to create a dictionary in a TXT file. At the moment I’m just using a vector in my script.js file.

The idea is to have one word on each line like this:

ANGEL
APPLE
HELLO
...

I created the .txt and am reading it from my JS

import { readFile } from "fs"; 
readFile("dictionary.txt", "utf8", (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    const randomLine = lines[Math.floor(Math.random() * lines.length)];
    console.log(randomLine);
  });

2

Answers


  1. import { readFile } from "fs";
    
    // Reading the file
    readFile("dictionary.txt", "utf8", (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
      
      // Splitting the file content into lines
      const lines = data.trim().split("n");
    
      // Choosing a random line
      const randomLine = lines[Math.floor(Math.random() * lines.length)].trim();
    
      console.log(randomLine); // Logs the randomly chosen line
    });
    

    This code reads the dictionary.txt file, splits ("n") its content into lines, selects a random line, and logs it to the console.

    Login or Signup to reply.
  2. I am not sure if there is real necessity to deal with file and store as text. I would recommend changing file structure to json and have array there.
    Example:

    import words from'./words.json' assert { type: "json" };
    
    const randomIndex= Math.floor(Math.random()*words.length);
    
    console.log(words[randomIndex])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search