1

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.

Aalexander
  • 4,987
  • 3
  • 11
  • 34
John
  • 13
  • 1
  • 2
  • You can't add the same key to an object. If you want to repeat a value, use an array in your JSON – GalAbra Jan 21 '21 at 07:25
  • Why would you want to repeat the objects in a json? – b3lg1c4 Jan 21 '21 at 07:25
  • writeFileSync is replacing the file when it already exist – Aalexander Jan 21 '21 at 07:25
  • 1
    Yes, `fs.appendFile` will append data. `fs.writeFileSync` would not. On a side note, what your code is doing right now : calling `finished()`, getting `undefined`, passing that `undefined` as the 3rd argument of `fs.writeFileSync` (so not very useful). Especially when the 3rd argument is supposed to be an options object. `Sync` means that the function does not take any callback in this case. It's synchronous – blex Jan 21 '21 at 07:28

1 Answers1

4

fs.writeFileSync() like fs.writeFile() will replace the file when it already exists. so when you call the function again it sees oh okay this file exists and is replacing it.

What you are looking for is fs.appendFileSync()

const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');

Note

Node.js developers prefer asynchronous methods over synchronous methods as asynchronous methods never block a program during its execution, whereas the later does. Blocking the main thread is malpractice in Node.js, thus synchronous functions should only be used for debugging or when no other options are available.

I would recommend to take a look at the Asynchronus Function appendFile()

fs.appendFile('message.txt', 'data to append', (err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});
Aalexander
  • 4,987
  • 3
  • 11
  • 34