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

如何用JavaScript读取txt字典文件并转为数组格式?

如何将字典文件转为JS数组

Node.js 环境(本地运行/桌面游戏)

你的字典文件和JS文件在同一目录,直接用Node.js内置的fs模块读取即可,步骤简单:

  1. 导入fs和path模块(无需额外安装)
  2. 读取文件内容,按换行符分割成数组
  3. 过滤空行,避免文件末尾的空行产生无效元素
const fs = require('fs');
const path = require('path');

// 构建文件路径,同目录下直接用文件名,或替换为fullPath
const dictPath = path.join(__dirname, 'dictionary.txt');

// 同步读取(适合游戏启动时初始化加载)
try {
  const fileContent = fs.readFileSync(dictPath, 'utf8');
  // 兼容Windows的\r\n和通用的\n换行符,同时过滤空行
  const wordArray = fileContent.split(/\r?\n/).filter(word => word.trim() !== '');
  console.log('字典加载完成,共', wordArray.length, '个单词');
  // 此处可将wordArray传入游戏逻辑
} catch (err) {
  console.error('读取字典失败:', err.message);
}

如果需要异步读取(避免阻塞主线程),用fs.promises.readFile:

const fs = require('fs').promises;
const path = require('path');

async function loadDictionary() {
  try {
    const dictPath = path.join(__dirname, 'dictionary.txt');
    const fileContent = await fs.readFile(dictPath, 'utf8');
    const wordArray = fileContent.split(/\r?\n/).filter(word => word.trim() !== '');
    return wordArray;
  } catch (err) {
    console.error('加载字典失败:', err.message);
    return [];
  }
}

// 调用加载方法
loadDictionary().then(wordArray => {
  console.log('字典数组就绪:', wordArray.slice(0, 5)); // 打印前5个单词验证
});

浏览器环境(网页游戏)

浏览器无法直接读取本地文件,需将dictionary.txt放在网页可访问的静态目录,用fetch请求加载:

async function loadDictionary() {
  try {
    // 同目录下直接用文件名,或替换为fullPath对应的URL
    const response = await fetch('dictionary.txt');
    if (!response.ok) throw new Error(`请求失败:${response.status}`);
    
    const fileContent = await response.text();
    const wordArray = fileContent.split(/\r?\n/).filter(word => word.trim() !== '');
    return wordArray;
  } catch (err) {
    console.error('加载字典失败:', err.message);
    return [];
  }
}

// 启动时加载字典
loadDictionary().then(wordArray => {
  // 将wordArray传入游戏逻辑使用
  console.log('字典已加载完成');
});

如果需要支持用户上传本地字典,用FileReader实现:

<!-- 页面添加文件选择器 -->
<input type="file" id="dictFileInput" accept=".txt">

<script>
document.getElementById('dictFileInput').addEventListener('change', async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  try {
    const fileContent = await file.text();
    const wordArray = fileContent.split(/\r?\n/).filter(word => word.trim() !== '');
    console.log('用户上传字典加载完成:', wordArray.length, '个单词');
    // 此处将wordArray传入游戏逻辑
  } catch (err) {
    console.error('读取上传文件失败:', err.message);
  }
});
</script>

关键注意事项

  • 确保字典文件编码为UTF-8,避免出现乱码
  • 用split(/\r?\n/)兼容Windows和Unix系统的换行符
  • 必须过滤空行,否则数组会包含无效的空字符串元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:15:52