0

I have a JSON file that I need to use as a database to add, remove and modify users, I have this code:

'use strict';

const fs = require('fs');

let student = {  
    id: 15,
    nombre: 'TestNombre', 
    apellido: 'TestApellido',
    email: 'TestEmail@gmail.com',
    confirmado: true 
};


let data = JSON.stringify(student, null, 2);
fs.writeFileSync('personas.json', data);

But that overwrites the JSON file, and I need to append as another object, so it continues with id 15 (last one was 14).

Here is a piece of the JSON file:

{
  "personas": [
    {
      "id": 0,
      "nombre": "Aurelia",
      "apellido": "Osborn",
      "email": "aureliaosborn@lovepad.com",
      "confirmado": false
    },
    {
      "id": 1,
      "nombre": "Curry",
      "apellido": "Jefferson",
      "email": "curryjefferson@lovepad.com",
      "confirmado": true
    },
  ]
}

How can I do this?

Nachot93
  • 63
  • 2
  • 10
  • 4
    Load the file first, keep it in memory and everytime you update that object you also store it back in the file. – MinusFour Aug 23 '18 at 23:30
  • There are some nice node_modules that can do the fs stuff for you and make it seem like you are just dealing with data. One that comes to mind is [lowdb](https://github.com/typicode/lowdb). – Mark Aug 23 '18 at 23:35
  • Is this a duplicate? https://stackoverflow.com/questions/36093042/how-do-i-add-to-an-existing-json-file-in-node-js – R01010010 Aug 23 '18 at 23:49

2 Answers2

2

Just require the file, push the student in the personas prop and writeFileSync it back.

'use strict';

const fs = require('fs');

let current = require('./personas.json');
let student = {
    id: 15,
    nombre: 'TestNombre',
    apellido: 'TestApellido',
    email: 'TestEmail@gmail.com',
    confirmado: true
};

current.personas.push(student);

// Make sure you stringify it using 4 spaces of identation
// so it stays human-readable.
fs.writeFileSync('personas.json', JSON.stringify(current, null, 4));
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
1

every time you want to write to the JSON file, you’ll need to read it first/parse it, update he Object and then write it to disk.

There’s a popular solution already handling that. Checkout lowdb

For the autoindexing - I believe the documentation suggests ways some helper libraries for this module to make that happen

Don’t reinvent the wheel!

Antiokus
  • 534
  • 3
  • 8