【发布时间】:2020-11-25 23:44:21
【问题描述】:
我有一个包含两个对象的 db.json 文件:
- 成员
- 团队
这是对象...
{
"members": [
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"jobTitle": "Driver",
"team": "Formula 1 - Car 77",
"status": "Active"
},
{
"id": 2,
"firstName": "Alex",
"lastName": "Sainz",
"jobTitle": "Driver",
"team": "Formula 1 - Car 78",
"status": "Active"
},
{
"id": 3,
"firstName": "Jeb",
"lastName": "Jackson",
"jobTitle": "Reserve Driver",
"team": "Formula 1 - Car 77",
"status": "Inactive"
}
],
"teams": [
{
"id": 1,
"teamName": "Formula 1 - Car 77"
},
{
"id": 2,
"teamName": "Formula 1 - Car 8"
},
{
"id": 3,
"teamName": "Formula 2 - Car 54"
},
]
}
我将添加一个新成员,我想以该对象为目标。
这是我的节点 JS 代码
// Submit Form!
app.post('/api/addMember', (req, res) => {
var isWriteable = 'is writable';
var isNotWriteable = 'is not writable';
console.log('REQ BODY: ', req.body);
request('http://localhost:3000/addMember', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
// console.log('RESPONSE!: ', response);
// console.log('All Members BODY!: ', body);
// console.log('REQ!: ', req);
// Now can we Write to the file
fs.access(dbFile, fs.constants.W_OK, (err) => {
console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);
if (!err) {
fs.open(dbFile, 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('DB JSON already exists');
dbFileNewMembers.push(dbFileMembers);
dbFileNewTeams.push(dbFileTeams);
console.log('DB FILE NEW JSON MEMBERS:', dbFileNewMembers);
console.log('DB FILE NEW JSON TEAMS:', dbFileNewTeams);
// saveNewMember(req.body)
// .then(result => {
//
// dbFileNewJSON.push(dbFileNewMembers);
// dbFileNewJSON.push(dbFileNewTeams);
//
// console.log('DB FILE NEW JSON:', dbFileNewJSON);
//
// console.log('RESULT OF SAVE NEW MEMBER: ', result);
// });
// fs.appendFile(dbFile, JSON.stringify(req.body), 'utf8', (err) => {
// if (err) {
// console.log('ERROR in saving a member: BODY: ', err);
// } else {
//
// console.log('SUCCESS saving new member!', req.body);
// }
// });
return;
}
throw err;
}
});
}
});
} else {
console.log('ERROR! DAMN! We blew it!', err);
}
});
});
我在注释掉的部分尝试了这两个功能。
我得到的是,新的 TEAM 成员被添加到对象的“末尾”而不是 TEAMS 对象的末尾。
这就是我正在尝试的。
我确实看过:
append json objects to file with nodejs
和
Add JSON objects to JSON object
但他们没有解决我的问题。
我知道我需要使用 appendFile() 这不是问题,但我需要附加到主 JSON 内部的特定对象,在这种情况下,团队和在未来的情况下,团队成员可能需要更新因此,更新特定的团队成员。
感谢您的帮助。
更新!
KG提了个建议,我修改了。
这里是变量:
var dbFileJSON = require('./db.json');
var obj = JSON.stringify(dbFileJSON);
console.log('DBFILE OBJ: ', obj);
console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
dbFileJSON['members'].push(newMember);
console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);
dbFileJSON = JSON.stringify(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);
dbFileJSON = JSON.parse(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);
console.log('UPDATED TEAM members: ', dbFileJSON);
结果直接添加到“MEMBERS”数组的底部!
这是我在实施 KG 的答案之前找到潜在答案的地方。
https://stackoverflow.com/questions/38716025/how-to-replace-old-json-object-with-a-new-one-with-nodejs
现在,剩下的唯一问题是:我需要替换 db.json,因为它没有这样做。
我的最后一个问题是:您如何将整个 JSON 文件替换为新文件的内容,因为我仍在获取原始文件。这是 server.js 文件的顶部,以更好地帮助了解我的位置。
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const path = require('path');
const request = require('request');
const fs = require("fs");
var hsts = require('hsts');
var xssFilter = require('x-xss-protection');
var nosniff = require('dont-sniff-mimetype');
var dbFileJSON = require('./db.json');
var dbFile = 'db.json';
var dbFileMembers = [];
var dbFileTeams = [];
const app = express();
app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(helmet({
noCache: false
}));
app.use(hsts({
maxAge: 15552000 // 180 days in seconds
}));
app.get('/api/members', (req, res) => {
request('http://localhost:3000/members', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
dbFileMembers.push(body);
console.log('BODY MEMBERS: ', body);
console.log('BODY MEMBERS DBFILEMEMBERS: ', dbFileMembers);
console.log('DBFILE: ', dbFileJSON);
console.log('SUCCESS! We got the members ', dbFileMembers);
} else {
console.log('ERROR getting MEMBERS: ', err);
}
});
});
// TODO: Dropdown! DONE!
app.get('/api/teams', (req, res) => {
request('http://localhost:3000/teams', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
dbFileTeams.push(body);
console.log('SUCCESS! We got the TEAMS! ', JSON.parse(dbFileTeams));
} else {
console.log('ERROR getting TEAMS: ', err);
}
});
});
这是我添加新会员的代码
// Submit Form!
app.post('/api/addMember', (req, res) => {
var isWriteable = 'is writable';
var isNotWriteable = 'is not writable';
console.log('REQ BODY: ', req.body);
request('http://localhost:3000/addMember', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
fs.access(dbFile, fs.constants.W_OK, (err) => {
console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);
if (!err) {
fs.open(dbFile, 'wx', (err, fd) => {
if (err) {
console.log('FD: ', fd);
if (err.code === 'EEXIST') {
console.error('DB JSON already exists');
console.log('DB FILE JSON MEMBERS:', dbFileMembers);
console.log('DB FILE JSON TEAMS:', dbFileTeams);
const newMember = req.body;
var obj = JSON.stringify(dbFileJSON);
console.log('DBFILE OBJ: ', obj);
console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
dbFileJSON['members'].push(newMember);
console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);
dbFileJSON = JSON.stringify(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);
dbFileJSON = JSON.parse(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);
console.log('UPDATED TEAM members: ', dbFileJSON);
}
}
});
}
});
} else {
console.log('ERROR! DAMN! We blew it!', err);
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/my-app/index.html'));
});
app.listen('8000', () => {
console.log('Vrrroooom Vrrroooom! Server starting!');
});
就是这样!任何进一步的评论都是花花公子!
【问题讨论】:
-
为什么不直接读取文件,添加对象并保存呢?这是一个选择吗?
-
是的,我可以阅读它,但是,使用 appendFile() 添加到对象的“成员”部分是我遇到的问题。我想添加一个新成员,而不是在整个 JSON 对象的底部,只是在成员对象的底部。这是一个好的开始 KG。
标签: javascript node.js json