无法通过fs模块读取TXT文件为字符串变量,求替代方案
读取TXT文件内容到字符串变量的替代方案
问题
尝试使用以下代码读取TXT文件并将内容存入可操作的字符串变量:
const fs = require('fs'); var file = fs.readFileSync("../word.txt", {encoding: 'utf8'}).toString()
但出现错误:Module not found: Error: Can't resolve 'fs',需要其他简便方法实现需求。
解决方案
前端环境(浏览器/Vite/Webpack等)
fs是Node.js内置模块,前端环境无法直接使用,可通过以下方式实现:
静态导入文本文件
若使用Vite,直接通过?raw后缀导入:import fileContent from '../word.txt?raw'; // fileContent 即为文件的字符串内容,可直接操作若使用Webpack,需先安装
raw-loader并完成配置,之后直接导入:import fileContent from '../word.txt';Fetch API异步读取
将TXT文件放在项目静态资源目录,通过网络请求获取内容:async function loadFile() { const res = await fetch('../word.txt'); const content = await res.text(); // 在此处对content进行操作 console.log(content); } loadFile();
Node.js环境(若报错为配置问题)
如果是Node.js环境下出现该错误,大概率是ES模块与CommonJS模块混用导致,改用ES模块写法即可:
import fs from 'fs/promises'; async function readTxtFile() { const content = await fs.readFile('../word.txt', 'utf8'); // 操作content变量 } readTxtFile();
内容的提问来源于stack exchange,提问作者Levin Kent
相关产品推荐
相关产品推荐

