1

I was wondering if there are some safe ways of writing to the JSON object properties using nodeJS. The following master piece I have came up with sometimes results in writing to the end of a JSON file (see attached). Perhaps, any alternatives?

for (const [key, value] of Object.entries(dependencyFileTypeScript)) {
  file['devDependencies'][key] = value;
}

fs.promises
  .writeFile(PACKAGE_FILE, JSON.stringify(file, null, 2))
  .catch((err) => {
    console.log(err);
});
{
...
}"@typescript": "15.6"
Aleksandrs
  • 11
  • 1
  • Are you *overwriting* an existing file perchance…? – deceze Sep 13 '21 at 12:34
  • yes, this is an existing file I access and then override – Aleksandrs Sep 13 '21 at 12:36
  • I believe that's the normal behavior, unless you need to sort your JSON object. If you need to sort your object, take a look at https://stackoverflow.com/questions/17684921/sort-json-object-in-javascript – brainoverflow Sep 13 '21 at 13:28
  • @brainoverflow is it? I guess the script should pass the values from the `for` loop TO the json object, but not outside of it. is there a chance I could ensure it reads the `devDependencies`? It's not about sorting :,) – Aleksandrs Sep 13 '21 at 14:03

0 Answers0