我正在通过POST路径接收JSON格式的事件,我想将这些事件保存在一个类似于‘Example.json’的文件中,并能够查询它.

我try 使用WriteFileSync,但它会重写整个文件.使用标志{FLAG:‘A+’}我可以保存多条记录,但当我try 请求‘Example.json’时,我收到错误‘Underful Token{in JSON’.

当文件只有一条记录时工作正常,但在第二条记录之后出现错误.

Code:

const filePath = './example.json';
const fs = require('fs');
const file = require('./example.json');

app.post('/events', (request, response) => {
  response.send(request.body);
  const contentString = JSON.stringify(request.body);
  return fs.writeFileSync(filepath, contentString, {flag: 'a+'});
});

example.json that works:

{"type":"call.new","call_id":"71252742562.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"} 

example.json (with two records) that stop working:

{"type":"call.new","call_id":"71252742562.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"}{"type":"call.ongoing","call_id":"71252731962.40019","code":"h9e8j7c0tl0j5eexi07sy6znfd1ponj4","direction":"inbound","our_number":"1130900336","their_number":"11999990000","their_number_type":"mobile","timestamp":"2020-04-01T00:00:00Z"} 

如何以可读的形式编写此JSON?这不会出现上述错误,并且可以执行要求.

有没有人能帮帮我?

推荐答案

try 读取JSON文件,解析它,向数组中添加新元素,然后覆盖该文件.

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

const FILE_PATH = path.join(__dirname, "./elements.json");

const file = fs.readFileSync(FILE_PATH);
const elements = JSON.parse(file);

const newElement = { id: Date.now() };
const updatedElements = [...elements, newElement];

fs.writeFileSync(FILE_PATH, JSON.stringify(updatedElements));

点击此处查看更多信息:https://nodejs.org/api/fs.html#fsappendfilesyncpath-data-options

Javascript相关问答推荐

可以的.是否可以在不预编译的情况下使用嵌套 Select 器?

*ngFor和@代表输入decorator 和选角闭合

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

如何从一个列表中创建一个2列的表?

Chromium会将URL与JS一起传递到V8吗?

MathJax可以导入本地HTML文档使用的JS文件吗?

我在我的Java代码中遇到了问题,代码的一部分看不到先前定义的对象

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

无法使用单击按钮时的useState将数据从一个页面传递到另一个页面

material UI按钮组样式props 不反射

本地库中的chartjs-4.4.2和chartjs-plugin-注解

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

Reaction组件在本应被设置隐藏时仍显示

未捕获的运行时错误:调度程序为空

Node.js API-queryAll()中的MarkLogic数据移动

更改agGRID/Reaction中的单元格格式

react 路由DOM有条件地呈现元素

如何在Reaction中清除输入字段

有没有办法在R中创建一张具有多个色标的热图?

如何为Reaction应用程序创建仅登录的路由?