Home > OS >  How to add json objects to empty json file in JavaScript
How to add json objects to empty json file in JavaScript

Time:01-30

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!

CodePudding user response:

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('');
});

CodePudding user response:

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
});
  •  Tags:  
  • Related