我正在创建一个类似 Wordle 的游戏,我需要在 TXT 文件中创建一个字典。目前我只是在 script.js 文件中使用向量。
这个想法是每一行都有一个单词,如下所示:
ANGEL
APPLE
HELLO
...
我创建了 .txt 并从我的 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);
});
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
});
这段代码读取dictionary.txt文件,分割(" ") 将其内容分成几行,选择随机行,并将其记录到控制台。