Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

402
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda