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: '[email protected]',
    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": "[email protected]",
      "confirmado": false
    },
    {
      "id": 1,
      "nombre": "Curry",
      "apellido": "Jefferson",
      "email": "[email protected]",
      "confirmado": true
    },
  ]
}

How can I do this?

3
  • 4
    Load the file first, keep it in memory and everytime you update that object you also store it back in the file. Commented Aug 23, 2018 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. Commented Aug 23, 2018 at 23:35
  • Is this a duplicate? stackoverflow.com/questions/36093042/… Commented Aug 23, 2018 at 23:49

2 Answers 2

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: '[email protected]',
    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));
Sign up to request clarification or add additional context in comments.

4 Comments

why the sync? just curious
To match the OP's preferred method. He/She already uses fs. writeFileSync in the question code snippet.
ah! ok, thought maybe it was really necesary :P
Thank you! This is exactly what I was looking for!
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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.