Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

404
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!