I want to create multiple objects in JSON with JS, even if the information is the same instead of replacing the old object.
Here is the code I am using.
student.js:
'use strict';
const fs = require('fs');
let student = {
name: 'Mike',
age: 25,
gender: 'Male',
department: 'English',
car: 'Honda'
};
let data = JSON.stringify(student);
fs.writeFileSync('file.json', data, finished());
function finished(err) {
console.log('success');
}
file.json (result of student.js):
{
"name": "Mike",
"age": 25,
"gender": "Male",
"department": "English",
"car": "Honda"
}
But when I run the code again with the same values, nothing happens and file.json remains the same as if I only ran it once.
How could I achieve something like this, for example, if I ran student.js three times (without changing any values in it)?
{
"name": "Mike",
"age": 25,
"gender": "Male",
"department": "English",
"car": "Honda"
} {
"name": "Mike",
"age": 25,
"gender": "Male",
"department": "English",
"car": "Honda"
} {
"name": "Mike",
"age": 25,
"gender": "Male",
"department": "English",
"car": "Honda"
}
Thanks.
fs.appendFilewill append data.fs.writeFileSyncwould not. On a side note, what your code is doing right now : callingfinished(), gettingundefined, passing thatundefinedas the 3rd argument offs.writeFileSync(so not very useful). Especially when the 3rd argument is supposed to be an options object.Syncmeans that the function does not take any callback in this case. It's synchronous