Save html-form data in json format in a .json file using node and express with javascript - Stack Overflow

Newbie in node and expressI am taking user input from html-form andtrying to append or push it in a

Newbie in node and express I am taking user input from html-form and trying to append or push it in a .json file. I have used jsonfile npm-package but it is not ing in a array format of json

code for appending-

var express = require('express');
var app = express();

//jade --> ejs -->html 
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

var jsonfile = require('jsonfile');    
var file = './userdata.json'


    //trying to write via form to json
    app.post('/gettingdata', function(req, res) {
        var user_id = req.body.usrid;
        var token = req.body.usrphone;
        var geo = req.body.usrdata;

        //start writing
        var obj = { name: user_id , phone: token, adress: geo }
        jsonfile.writeFileSync(file, obj, {flag: 'a'});

        //default
        //res.send(user_id + ' ' + token + ' ' + geo);
    }); 

html -

<body>
    <form action="/gettingdata" method="post">
            Name:<input type="text" name="usrid" /><br>
            Phone:<input type="text" name="usrphone" /><br>
            RData:<input type=="text" name="usrdata" /><br>
            <input type="submit" value="Submit" >
    </form>
</body>

json appearing as-

{"name":"name1","phone":"8989898989","adress":"random1"}
{"name":"name1","phone":"767656568","adress":"randomdata1"}
{"name":"name1","phone":"767656568","adress":"randomdata1"}

there are no mas appearing between objects and no square brackets. I need them to be able to make parsing possible, so that I can dynamically edit and delete data from my front-end later. Suggest any link,method or npm package to do so.If question repeated share the link of that too

Newbie in node and express I am taking user input from html-form and trying to append or push it in a .json file. I have used jsonfile npm-package but it is not ing in a array format of json

code for appending-

var express = require('express');
var app = express();

//jade --> ejs -->html 
app.engine('html', require('ejs').renderFile);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

var jsonfile = require('jsonfile');    
var file = './userdata.json'


    //trying to write via form to json
    app.post('/gettingdata', function(req, res) {
        var user_id = req.body.usrid;
        var token = req.body.usrphone;
        var geo = req.body.usrdata;

        //start writing
        var obj = { name: user_id , phone: token, adress: geo }
        jsonfile.writeFileSync(file, obj, {flag: 'a'});

        //default
        //res.send(user_id + ' ' + token + ' ' + geo);
    }); 

html -

<body>
    <form action="/gettingdata" method="post">
            Name:<input type="text" name="usrid" /><br>
            Phone:<input type="text" name="usrphone" /><br>
            RData:<input type=="text" name="usrdata" /><br>
            <input type="submit" value="Submit" >
    </form>
</body>

json appearing as-

{"name":"name1","phone":"8989898989","adress":"random1"}
{"name":"name1","phone":"767656568","adress":"randomdata1"}
{"name":"name1","phone":"767656568","adress":"randomdata1"}

there are no mas appearing between objects and no square brackets. I need them to be able to make parsing possible, so that I can dynamically edit and delete data from my front-end later. Suggest any link,method or npm package to do so.If question repeated share the link of that too

Share Improve this question asked Jul 21, 2017 at 12:41 sndpkprsndpkpr 6398 silver badges17 bronze badges 2
  • Hi, wele to Stack Overflow! As a side-note, try to avoid the *Sync variants of functions and learn asynchronous patterns; it will serve you really well later in your JavaScript/node career. – msanford Commented Jul 21, 2017 at 12:43
  • Sandeep, I added a new answer with some code. – msanford Commented Jul 21, 2017 at 13:55
Add a ment  | 

2 Answers 2

Reset to default 3

I will expand on Shil's answer with some code:

// 1. Read the existing file
fs.readFile(file, (err, data) => {
    if (err && err.code === "ENOENT") {
        // But the file might not yet exist.  If so, just write the object and bail
        return fs.writeFile(file, JSON.stringify([obj]), error => console.error);
    }
    else if (err) {
        // Some other error
        console.error(err);
    }    
    // 2. Otherwise, get its JSON content
    else {
        try {
            const fileData = JSON.parse(data);

            // 3. Append the object you want
            fileData.push(obj);

            //4. Write the file back out
            return fs.writeFile(file, JSON.stringify(fileData), error => console.error)
        } catch(exception) {
            console.error(exception);
        }
    }
});

This is just a quick, illustrative example: it is inefficient as the file grows as it has to read and write the entire file every single time.

Note that this will create a file which contains an array of objects, which is how you make lists of objects in JSON. So your final output will look like this:

[
  {"name":"name1","phone":"8989898989","adress":"random1"},
  {"name":"name1","phone":"767656568","adress":"randomdata1"},
  {"name":"name1","phone":"767656568","adress":"randomdata1"}
]

Seems the library u are using can't do that thing. In both methods I find this:

 var str = JSON.stringify(obj, options.replacer, spaces) + '\n'
 //not sure if fs.writeFileSync returns anything, but just in case
 return fs.writeFileSync(file, str, options)

where it writes into file the string you have just passed into the function, so it doesn't evaluate what it is already written into the file. So it will write one json every time you call the function. It won't continue to add elements to the existing json. You should do a custom function to do it.

You could do this:

  1. retrive what it's already in the file
  2. parse into json
  3. append the json object you want to add
  4. stringify the result and save it into the file replacing what was writing first.

edit:

sources: writeFile / writeFileSync

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131651a4613001.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信