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

如何为纯HTML/CSS/JS项目添加Node.js以实现fs模块功能?

给纯前端项目添加Node.js并使用fs操作JSON文件的步骤

1. 安装Node.js

下载Node.js的LTS版本(长期支持版)完成安装,安装后打开终端,输入以下命令验证安装结果:

node -v
npm -v

能正常输出版本号即说明安装成功。

2. 初始化Node.js项目

进入你的项目根目录,在终端执行:

npm init -y

该命令会自动生成package.json文件,用于管理项目依赖与运行脚本。

3. 编写操作JSON的Node.js脚本

在项目根目录新建文件(比如jsonHandler.js),用Node.js的fs模块实现JSON文件的读写与修改,示例代码如下:

基础读写示例

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

// 定义JSON文件路径,避免跨平台路径问题
const jsonFile = path.join(__dirname, 'data.json');

// 写入初始JSON数据(文件不存在则自动创建,存在则覆盖)
const initialData = {
  items: [],
  lastUpdated: new Date().toISOString()
};
fs.writeFileSync(jsonFile, JSON.stringify(initialData, null, 2), 'utf8');
console.log('初始JSON文件已创建');

// 修改JSON文件的函数
function updateJson(newContent) {
  // 先读取现有数据
  let currentData = {};
  try {
    currentData = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
  } catch (err) {
    console.log('未找到现有文件,将基于新内容创建');
  }
  // 合并新内容到现有数据
  Object.assign(currentData, newContent);
  // 写回文件
  fs.writeFileSync(jsonFile, JSON.stringify(currentData, null, 2), 'utf8');
  console.log('JSON文件已更新');
}

// 调用修改函数,添加新条目
updateJson({
  items: [...initialData.items, { id: 1, name: '测试条目' }]
});

4. 运行脚本

在终端执行以下命令运行脚本:

node jsonHandler.js

执行后,项目根目录会生成/更新data.json文件,控制台会输出操作提示。

5. 若需和前端页面交互

浏览器端JavaScript无法直接访问Node.js的fs模块,如果要让前端页面触发JSON文件操作,需要搭建简单HTTP服务:

  1. 安装Express轻量Web框架:
npm install express
  1. 新建server.js文件,编写服务代码:
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

// 解析前端发送的JSON请求体
app.use(express.json());
// 托管前端静态资源(将你的HTML/CSS/JS文件放到项目根目录的public文件夹)
app.use(express.static(path.join(__dirname, 'public')));

// 接口:获取JSON数据
app.get('/api/get-data', (req, res) => {
  const jsonFile = path.join(__dirname, 'data.json');
  try {
    const data = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: '读取数据失败' });
  }
});

// 接口:更新JSON数据
app.post('/api/update-data', (req, res) => {
  const jsonFile = path.join(__dirname, 'data.json');
  const updateData = req.body;
  let currentData = {};
  
  try {
    currentData = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
  } catch (err) {
    console.log('无现有数据,将创建新文件');
  }
  
  Object.assign(currentData, updateData);
  fs.writeFileSync(jsonFile, JSON.stringify(currentData, null, 2), 'utf8');
  res.json({ message: '数据更新成功', data: currentData });
});

// 启动服务
app.listen(port, () => {
  console.log(`服务已启动,访问 http://localhost:${port} 打开前端页面`);
});
  1. 将前端文件全部移入项目根目录的public文件夹,终端执行:
node server.js

之后在浏览器访问http://localhost:3000,前端可通过fetch调用接口操作JSON文件,示例如下:

// 前端获取数据
fetch('/api/get-data')
  .then(res => res.json())
  .then(data => console.log(data));

// 前端更新数据
fetch('/api/update-data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ lastUpdated: new Date().toISOString() })
})
.then(res => res.json())
.then(result => console.log(result));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:33:35