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

大憨熊 提交于 2019-12-08 02:27:51

问题


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 coming 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 commas 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


回答1:


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"}
]



回答2:


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



来源:https://stackoverflow.com/questions/45237999/save-html-form-data-in-json-format-in-a-json-file-using-node-and-express-with-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!