I'm trying to save multiple data from different files into database.db
without any libraries such as MongoDB or MySQL.
A problem is database.db
keeps overwriting when it receives new data from each instance.
{"score":12} // It only saves the last data.
Furthermore, when I refresh the browser constantly, sometimes the data is going to merge in a weird pattern like this:
{"score":12}p"} // That p is the last letter of a word from first instance, 'Temp'.
This is how I've done in the code:
// instance1.js
class A {
constructor(name) {
this.name = name
this.post();
}
async post() {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this)
};
const response = await fetch('/', options);
const json = await response.json();
}
}
let newa = new A('Temp');
// instance2.js
class B {
constructor(score) {
this.score = score
this.post();
}
async post() {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this)
};
const response = await fetch('/', options);
const json = await response.json();
}
}
let newb = new B(12);
// server.js
const express = require('express');
const fs = require('fs');
const app = express();
app.listen(3000, () => console.log('initialized . . .'));
app.use(express.static('public'));
app.use(express.json({limit: '10mb'}));
app.post('/', (request, response) => {
var instance = request.body,
object = JSON.stringify(instance);
fs.writeFile('database.db', object, () => {
console.log(object);
});
response.json(request.body);
})
My goal is to save objects into the database for sending back to the client-side javascript.
Are there any ways to store the data w/o overwriting and how to prevent unwanted merging?
I my opinion you should change in post
request writeFile
to appendFile
app.post('/', (request, response) => {
var object = JSON.stringify(request.body);
fs.appendFile('database.db', object, (data) => {
console.log(data);
});
response.json(request.body);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.