【问题标题】:Writing data in json file array throw node.js在 json 文件数组中写入数据抛出 node.js
【发布时间】:2023-01-11 08:31:22
【问题描述】:

我想在我的 posts.json 文件中写入数据并抛出 index.js node.js 文件,并且该 id 会自动提供给发布。

这是 index.js 文件:

const { ALL } = require('dns');
const { text } = require('express');
const express = require('express');
const fs = require('fs')
const app = express();

app.get('/', (req, res) => {
  res.send('To see all posts add to url /api/posts.')

});
app.get('/api/posts', (req, res) => {
  fs.readFile('posts.json', 'utf8', (err, data) => {
  if (err) {
  console.error(err);
  }else{
  res.json(JSON.parse(data))};
});
});

app.get('/api/posts/:id', (req, res) => {
  fs.readFile('posts.json', 'utf8', (err, data) => {
  if (err) {
  console.error(err);
  }else{
    const resArray = JSON.parse(data)
    const posts = resArray.find(posts => posts.id == req.params.id)
    res.send(posts)
}});
});

app.post('/api/posts', (req, res) => {
  fs.writeFile('posts.json', 'utf8', (err, data) => {
  if (err) {
  console.error(err);
  }else{

// here should go the code

}});
});

app.listen(3000, () => {
  console.log('server started'); 
});

我尝试了很多变体,但没有一个起作用。 这是 posts.json 文件部分:

[
    {
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
      "id": 2,
      "title": "qui est esse",
      "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    },
...
]

我需要一个选项卡中的字段,用于在所有帖子下输入标题和正文。

【问题讨论】:

  • writeFile 的第二个参数应该是你要写入的数据,第三个参数是选项。 see Node.js doc

标签: javascript node.js json


【解决方案1】:

因为你想先写一个 JSON 数据,你需要读取 JSON 结构来修改它,如下所示:

app.post('/api/posts', (req, res) => {
    fs.readFile('posts.json', 'utf8', (err, data) => {
      if (err) {
        console.error(err);
      } else {
        const resArray = JSON.parse(data)
        resArray.push(data)
        fs.writeFile('posts.json', JSON.stringify(resArray));
    }});
});

添加新帖子时,您可以轻松地从 resArray 计算您的 ID,例如,您可以找到最大先前 ID 并向其添加一个,如下所示:

data.id = Math.max(...resArray.map(item => item.id)) + 1

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多