Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

401
Vistas
How to add json objects to empty json file in JavaScript

I am making a login form using HTML and JavaScript and I want to add the login information like username and password to a JSON file using JavaScript. The object would be of the form:

{username : password}

Here is the code I have so far in JavaScript:

const fs = require("fs");
let usersjson = fs.readFileSync("data.json", "utf8");

let obj = {};

app.post("/login", validate, (req, res) => {
  let email = req.body.email;
  let password = req.body.password;
  obj.email = email;
  obj.password = password;
  let user = JSON.parse(obj);
  user.push(obj);
  JSON.stringify(user);
  fs.writeFileSync("data.json", usersjson, "utf8");

I am using Node.js and Express.js as my backend.

Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Node.js is single-thread so using readFileSync/writeFileSync is maybe bad idea. Sorry if I incorrect understand your question. Do you want create an empty object or just write in to a file?

app.post('/login', validate, (req, res) => {
    const {email, password} = req.body;
    const user = {};
    user.email = email;
    user.password = password;
    // need try/catch 
    fs.writeFileSync('data.json', JSON.stringify(user), 'utf8');
    // need return answer from server JSON.stringify(user)
    res.json('');
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

If I understood correctly, you want to add the user info to your data.json file every time a user logs in. if so:

app.post('/login', validate, (req, res) => {
    let email = req.body.email;
    let password = req.body.password;
    let user = {email: email, password: password}

    const previousData = JSON.parse(fs.readFileSync("./data.json", 'utf8'))
    previousData.push(user)

    fs.writeFileSync("./data.json", JSON.stringify(previousData), "utf8");
   // send a response
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda