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

无法通过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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:15:07