You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从TXT文件中读取单行内容?(类Wordle游戏开发场景)

解决从TXT词典文件读取随机单行单词的问题

你的代码核心问题是未将读取到的文件内容转换为行数组,直接使用了未定义的lines变量。以下是修正后的实现方案,分Node.js和浏览器两种环境说明:

Node.js 环境(使用fs模块)

读取文件后,通过换行符\n分割字符串得到每行单词的数组,同时过滤掉空行(避免文件末尾的空白行干扰),再随机选取一行:

import { readFile } from "fs"; 

readFile("dictionary.txt", "utf8", (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    // 分割内容为行数组,过滤空行
    const lines = data.split('\n').filter(line => line.trim() !== '');
    
    // 校验数组是否有效
    if (lines.length === 0) {
      console.error("词典文件中无有效单词");
      return;
    }
    
    // 随机选取一行
    const randomWord = lines[Math.floor(Math.random() * lines.length)];
    console.log(randomWord);
});

注意:确保dictionary.txt的路径相对于当前脚本的执行目录,若路径不对会触发读取错误。

浏览器环境(使用Fetch API)

如果你的Wordle类游戏是前端网页应用,不能直接使用Node.js的fs模块,需用fetch读取文件:

fetch('dictionary.txt')
  .then(response => {
    if (!response.ok) throw new Error("无法读取词典文件");
    return response.text();
  })
  .then(data => {
    const lines = data.split('\n').filter(line => line.trim() !== '');
    
    if (lines.length === 0) {
      console.error("词典文件中无有效单词");
      return;
    }
    
    const randomWord = lines[Math.floor(Math.random() * lines.length)];
    console.log(randomWord);
  })
  .catch(err => console.error(err));

内容的提问来源于stack exchange,提问作者Matias Sanabria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:27:36