如何用JavaScript逐行读取文件内容保存为字符串列表并打乱顺序
实现方案
JS运行环境不同,文件读取逻辑有明显差异,以下是两种常见场景的完整实现:
1. Node.js 环境(适用于本地脚本/后端场景)
无需引入第三方依赖,直接用Node原生模块即可实现:
const fs = require('fs'); // Fisher-Yates 洗牌算法(随机打乱数组,分布均匀无偏差) function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } // 读取文件+处理+打乱的封装方法 function getShuffledWords(filePath) { // 同步读取文件内容,按UTF-8编码解析 const fileContent = fs.readFileSync(filePath, 'utf8'); // 按换行符拆分,过滤空行和无效空格 const wordList = fileContent.split(/\r?\n/) .map(word => word.trim()) .filter(word => word.length > 0); // 返回打乱后的单词列表 return shuffleArray(wordList); } // 调用示例,替换为你的实际txt文件路径 const shuffledWords = getShuffledWords('./words.txt'); console.log(shuffledWords);
说明:
- 用
\r?\n拆分换行兼容Windows和Unix系统的换行格式 - 加
trim()和空行过滤是为了排除文件里的空行、首尾空格等无效内容 - Fisher-Yates算法是目前公认的公平洗牌算法,比
arr.sort(() => Math.random() - 0.5)的写法随机分布更均匀,没有排序逻辑带来的偏差
2. 浏览器端环境(适用于前端页面,用户手动上传文件场景)
浏览器出于安全限制不能直接读取用户本地文件,需要通过文件上传控件触发读取:
<!-- 页面文件上传控件 --> <input type="file" id="wordFileInput" accept=".txt">
// 洗牌算法和Node端通用 function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } // 监听文件上传事件 document.getElementById('wordFileInput').addEventListener('change', e => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = event => { const fileContent = event.target.result; // 拆分、过滤逻辑和Node端完全一致 const wordList = fileContent.split(/\r?\n/) .map(word => word.trim()) .filter(word => word.length > 0); const shuffledWords = shuffleArray(wordList); // 此处可添加拿到打乱列表后的后续业务逻辑 console.log(shuffledWords); }; reader.readAsText(file); });
说明:
accept=".txt"限制只能上传txt文件,避免用户上传其他格式的无效文件FileReader.readAsText()方法默认按UTF-8编码解析文本,和Node端的解析逻辑对齐
内容的提问来源于stack exchange,提问作者Laily
相关产品推荐
相关产品推荐

