node.js - 如何从json文件中读取和写入数据

标签 node.js json

我想用nodejs编写一个json文件,但我不知道,因为我是初学者

问题是当我尝试将数据添加到json文件时,数据不会增加而是被覆盖,例如,我有数据“a”(总数据= 1)然后我尝试添加新数据“b” “(总数据= 1)因为数据“a”被数据“b”覆盖,所以我的数据永远不会增加,总共只有1个数据

这是目录/user/userData.json 中我的 json 结构

[
 {
  "username": "john",
  "password": "123qwejkl",
  "nama": "john somelastname",
  "no": "0128749726",
  "email": "john@gmail.com",
  "caption": "life is never flat"
 }
]

这是我的nodejs代码

 //const data = fs.readFileSync('./user/userData.json')
 //const jsonData = JSON.parse(data)

 app.post('/user', (req, res)=>{
   const username = req.body.username
   const password = req.body.password
   const name = req.body.nama
   const no = req.body.no
   const email = req.body.email
   const caption = req.body.caption


   const sendData = [{
    username:username,
    password:password,
    name:name,
    no:no,
    email:email,
    caption:caption
   }]


    const sendJSON = JSON.stringify(sendData, null,2)
    fs.writeFile('./user/userData.json', sendJSON)

    res.send(sendData)

 })

我知道我的代码中缺少某些内容,所以请帮助我如何从 json 文件读取数据然后将新数据写入 json 文件

最佳答案

为了不覆盖已经存在的数据,您必须从文件系统读取文件,将其解析为 JSON,将新元素(用户)推送到数组并将结果写入文件系统:

//after you have created sendData object
fs.readFile('./user/userData.json', 'utf8', function (err, data) {
  if (err) throw err;
  output = JSON.parse(data);
  output.push(sendData[0]);
  const sendJSON = JSON.stringify(output, null, 2);
  fs.writeFile('./user/userData.json', sendJSON, function(err){
    if (err) throw err;
    res.send(sendJSON)
  });
});

我可以看到您正在创建某种用户注册系统。请注意,不建议在 Web 应用程序中使用文件来存储数据。它可能会导致性能差、容错能力低以及可能的并发数据访问问题(竞争条件)。

根据您的情况,想象以下情况(分步骤):

  1. 用户 1 使用您的 /user 端点进行注册
  2. 处理用户 1 请求等待 I/O 操作 readFile
  3. 与此同时,用户 2 使用相同的 /user 端点进行注册
  4. 处理用户 2 请求等待 I/O 操作 readFile
  5. 处理用户 1 请求继续执行(运行回调)并使用 writeFile 保存文件(初始 + 用户 1 数据)
  6. 处理用户 2 请求继续执行(运行回调)并使用 writeFile 覆盖文件(初始 + 用户 2 数据)

因此,用户 1 的数据将丢失(包含用户 1 数据的文件将被覆盖)。

几乎所有数据库都会防止这种情况发生。

我建议您研究以下主题:JS 异步代码执行、JS 回调、数据并发、在 Node.js 中使用数据库(MongoDB 是一个很好的开始)。

关于node.js - 如何从json文件中读取和写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56201934/

相关文章:

node.js - Node js 中的实体太大(Express.js 版本为 4.16.1)

javascript - Stripe : Must provide source or customer

jquery - 迭代 Json 对象以获取第一个对象

c - json-c 解析 - 取消引用指向不完整类型的指针时出错

javascript - 具有动态数组名称的数据表 JSON

javascript - Jquery toggle() 不适用于 YouTube 订阅按钮

javascript - 如何对数组应用映射操作来添加属性?

node.js - 找不到模块 'ejs' - Heroku 上的 Node.js 应用程序

node.js - 避免 created_at 和 updated_at 由 sequelize 自动生成

ios - 使用 SBJSON 解析 JSON,问题