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

无法在HTML网站中使用Node.js的require():技术求助

问题原因与解决方案

首先明确核心问题:GitHub Pages仅支持托管静态HTML/CSS/JS资源,完全不运行Node.js后端代码,浏览器环境里根本没有Node.js专属的require()函数,这就是你报错的直接原因。

而且fs是Node.js的服务器端内置模块,只能在服务器环境执行;同时浏览器出于安全限制,本身就不允许前端JS直接读写本地或服务器文件,所以你在前端代码里调用fs模块从逻辑上就行不通。

给你几个可行的解决思路:

1. 借助第三方后端服务存储数据

使用免费的后端存储服务(比如Firebase Realtime Database、Supabase),前端通过fetch或axios把用户输入的数据发送到服务接口,由服务负责存储。前端示例代码:

<form id="inputForm">
  <input type="text" id="userInput" placeholder="输入内容">
  <button type="submit">保存</button>
</form>

<script>
document.getElementById('inputForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const inputValue = document.getElementById('userInput').value;
  
  await fetch('你的后端服务接口地址', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ content: inputValue })
  });
  
  alert('保存成功');
});
</script>

2. 自行搭建Node.js后端并部署

用Express写一个简单的后端接口,接收前端传来的数据后用fs模块写入文件,再把后端部署到Vercel、Railway这类免费平台。

后端示例代码(Express):

const express = require('express');
const fs = require('fs');
const app = express();
app.use(express.json());

app.post('/save-data', (req, res) => {
  const content = req.body.content + '\n';
  fs.appendFile('data.txt', content, (err) => {
    if (err) {
      res.status(500).send('保存失败');
      return;
    }
    res.send('保存成功');
  });
});

app.listen(process.env.PORT || 3000);

前端依然用上面的fetch代码,把接口地址替换成你部署后的后端地址即可。

3. 客户端本地存储(仅当前用户可见)

如果只需要在用户自己的浏览器里保存数据,不需要同步到服务器,可以用localStorage:

<form id="inputForm">
  <input type="text" id="userInput" placeholder="输入内容">
  <button type="submit">保存</button>
</form>

<script>
document.getElementById('inputForm').addEventListener('submit', (e) => {
  e.preventDefault();
  const inputValue = document.getElementById('userInput').value;
  // 读取已有存储数据
  let savedData = localStorage.getItem('userInputs') || '';
  // 追加新内容
  savedData += inputValue + '\n';
  localStorage.setItem('userInputs', savedData);
  alert('已保存到本地');
});
</script>

这种方式数据仅存在用户当前浏览器中,更换设备或清除缓存后会丢失,适合无需共享数据的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:47:03