[英]I am having trouble appending dynamic data to my JSON file
I have been having a bit of trouble appending new dynamic data to a JSON file.我在将新的动态数据附加到 JSON 文件时遇到了一些麻烦。 To sum up my project, I take in the projectName from an input form at the /new page.
总结一下我的项目,我从/new页面的输入表单中获取 projectName。 My API is then using the node.js's fs module to create a new JSON file with which I can then append the new dynamic data upon subsequential requests to my form.
然后我的 API 正在使用 node.js 的 fs 模块创建一个新的 JSON 文件,然后我可以使用它 append 对我的表单进行后续请求时获得新的动态数据。 The variables are 1) projectName (is taken in from my form), 2) activeUser (which is programmed in through an environmental variable), 3) is the date of the request which I am acquiring through a timestamp variable with this function:
变量是 1) projectName (取自我的表单), 2) activeUser (通过环境变量编程), 3) 是我通过时间戳变量获取的请求的日期与此 function:
const timestamp = (JSON.parse(JSON.stringify(new Date())));
All three of these variables seem to print correctly for 2 subsequent requests and then on the third form submission there seems to be no new data appending to the JSON file.对于 2 个后续请求,所有这三个变量似乎都正确打印,然后在第三个表单提交时,似乎没有新数据附加到 JSON 文件。 However i am relatively new to node.js and I can't seem to figure out where I am messing this up.
但是我对 node.js 比较陌生,我似乎无法弄清楚我在哪里搞砸了。
This is my API这是我的 API
pages/api/demos/index.js页面/api/demos/index.js
import dbConnect from '../../../lib/dbConnect';
import Demo from '../../../models/Demo';
import fs from 'fs';
export default async function handler(req, res) {
const {
query: { id },
method,
} = req
await dbConnect()
switch (method) {
case 'POST':
try {
//check if file exist
if (!fs.existsSync('projects.json')) {
//create new file if not exist
fs.closeSync(fs.openSync('projects.json', 'w'));
}
// read file
const timestamp = (JSON.parse(JSON.stringify(new Date())));
const newFileName = req.body.projectName;
const activeUser = process.env.ACTIVE_USERNAME;
const file = fs.readFileSync('projects.json')
const data = {
"projects": [
{
"username": activeUser,
"pages": [
{
"display": "routes",
"subpages": [
{
"date": timestamp,
"route": newFileName,
"display": newFileName
}
]
}
]
}
]
}
//check if file is empty
if (file.length == 0) {
//add data to json file
fs.writeFileSync("projects.json", JSON.stringify([data]))
} else {
//append data to jso file
const json = JSON.parse(file.toString())
//add json element to json object
json.push(data);
fs.appendFileSync("projects.json", JSON.stringify(data))
}
const demo = await Demo.create(
req.body
)
res.status(201).json({ success: true, data: demo })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
break
}
}
After the first form submission my JSON file projects.json looks like在第一次提交表单后,我的 JSON 文件projects.json看起来像
[
{
"projects": [
{
"username": "projectmikey",
"pages": [
{
"display": "routes",
"subpages": [
{
"date": "2022-09-12T19:03:09.547Z",
"route": "1",
"display": "1"
}
]
}
]
}
]
}
]
and then after the 2nd form submission然后在第二次提交表单之后
[
{
"projects": [
{
"username": "projectmikey",
"pages": [
{
"display": "routes",
"subpages": [
{
"date": "2022-09-12T19:03:09.547Z",
"route": "1",
"display": "1"
}
]
}
]
}
]
}
]{
"projects": [
{
"username": "projectmikey",
"pages": [
{
"display": "routes",
"subpages": [
{
"date": "2022-09-12T19:03:24.466Z",
"route": "2",
"display": "2"
}
]
}
]
}
]
}
Oddly it seems to work for two form submissions and then the data stops appending to my file.奇怪的是,它似乎适用于两个表单提交,然后数据停止附加到我的文件中。 This is after the third attempt, (no change to the file)
这是第三次尝试之后,(文件没有变化)
[
{
"projects": [
{
"username": "projectmikey",
"pages": [
{
"display": "routes",
"subpages": [
{
"date": "2022-09-12T19:03:09.547Z",
"route": "1",
"display": "1"
}
]
}
]
}
]
}
]{
"projects": [
{
"username": "projectmikey",
"pages": [
{
"display": "routes",
"subpages": [
{
"date": "2022-09-12T19:03:24.466Z",
"route": "2",
"display": "2"
}
]
}
]
}
]
}
It seems to stop working at all when I remove the pair of brackets around the initial JSON object.当我移除初始 JSON object 周围的一对括号时,它似乎完全停止工作。 The line I am refering to is
fs.writeFileSync("projects.json", JSON.stringify([data]))
我指的是
fs.writeFileSync("projects.json", JSON.stringify([data]))
I could really use another pair of eyes on this so I can see where I am messing this up.我真的可以用另一双眼睛来解决这个问题,这样我就可以知道我在哪里搞砸了。 lol Thanks in advance for your time...
大声笑提前感谢您的时间...
Although it feels like you are "appending" to the file, you are actually doing something more complicated.虽然感觉像是在“附加”到文件中,但实际上你在做一些更复杂的事情。
eg before state:例如在 state 之前:
[ "one", "two" ]
desired after-state:所需的后状态:
[ "one", "two", "three" ]
Notice that you can't just append text to the before-state JSON because there's already that pesky ]
terminating the whole object.请注意,您不能只将 append 文本写入前状态 JSON,因为已经有那个讨厌的
]
终止整个 ZA8CFDE6331BD59EB2AC96F8911C4B6666Z。
Some failed attempts might look like:一些失败的尝试可能如下所示:
[ "one", "two" ][ "three" ]
This is invalid because there are two root objects.这是无效的,因为有两个根对象。
[ "one", "two" ], "three" ]
That's no good either.那也不好。 The
]
at the end of the original file needs to be overwritten or removed, so there's no way to just append.原始文件末尾的
]
需要被覆盖或删除,因此无法仅使用 append。 I suppose technically you could seek to the position of the final ]
and then continue writing an incomplete object from there.我想从技术上讲,您可以寻找最终的 position
]
,然后从那里继续编写不完整的 object。 But this is very awkward to remove the final ]
from the source and to remove the initial [
from the chunk you're trying to append.但是从源中删除最后的
]
并从您尝试 append 的块中删除初始的[
是非常尴尬的。 It's just a difficult approach.这只是一个困难的方法。
push
into the array to add another element)push
入数组以添加另一个元素) /* In Node.js: const fs = require('fs'); try { initialJSON = fs.readFileSync('example.json'); } catch (ignore) { initialJSON = '[]'; } */ /* Mocked for this example: */ initialJSON = '["one","two"]'; // Common obj = JSON.parse(initialJSON); obj.push("three"); finalJSON = JSON.stringify(obj); /* In Node.js: fs.writeFileSync('example.json', finalJSON); */ /* Mocked for this example: */ console.log(finalJSON);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.