-2

I have json file as

{
    "username1": "user1",
    "password1": "***",

    "username2": "user2",
    "password2": "****",

    "username3": "user3",
    "password3": "*****"
}

I am reading my file like this :

var fs = require('fs');
var contents = fs.readFileSync('./actions/writeTo.json');
var jsonContent = JSON.parse(contents);            
console.log(jsonContent.username2);

But I am not able to figure out how to write to this file, say I want to update username3. How do i do that?

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97

5 Answers5

2

You do exactly the opposite of what you do to read it.

You use JSON.stringify to turn your data structure into JSON. Then you use fs.writeFile to write it to the file.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0
var fs = require('fs');
var contents = fs.readFileSync('./actions/writeTo.json');
var jsonContent = JSON.parse(contents);            
console.log(jsonContent.username2);

jsonContent.username3 = 'Changed';
jsonContent.username4 = 'New User';

var dest = '../file.json';

var fd = fs.createWriteStream(dest, {
    flags: 'w',
    autoClose: true
});

fd.write(JSON.stringify(jsonContent));
fd.end('\n');
fd.on('finish', () => {
    //Handle success
}).on('error', (err) => { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
});
Govan
  • 7,751
  • 5
  • 26
  • 42
0

Well first of all, I hope this is just for educational purposes, and you do not plan to manage user accounts this way, storing plaintext passwords in a json file.

Second, you seem to misuse the structure of JSON. Why to have user1, user2, user3 keys when you can have an array? It would be much better if you'd arrange this data like this:

{
    "users": [
        {
            "username": "Alice",
            "anything-but-not-plaintext-password": "Puppies and kittens"
        },
        {
            "username": "Bob",
            "anything-but-not-plaintext-password": "Cheese nuggets"
        }
    ]
}

Finally, you can write a json to a file in nodejs using fs.writeFileSync:

var fs = require('fs');
var jsonContent = {}; // Here is your loader and modifier code
var jsonString = JSON.stringify(jsonContent, null, 4); // Pretty printed
fs.writeFileSync("./actions/writeTo.json", jsonString);

But still, this is how you must not handle user credentials. Here is a pretty good tutorial on the topic: Node.js authentication series: Passport local strategy using email and password.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
0

You can use code as below:

jsonContent.username3 = 'NewUsername';

var body = JSON.stringify(jsonContent);
var localPath = './actions/writeTo.json';
fs.writeFile(localPath,body,function(err){});
André Dion
  • 21,269
  • 7
  • 56
  • 60
Renju
  • 119
  • 1
  • 5
0

do npm install jsonfile

var jsonfile = require('jsonfile');  
var config = require('../support/config.json');  

function writeToConfig(name, fileObj) {  

fileObj.username3 = name;
//console.log('This is to WriteFile Stringified fileObj:' +'\n\n' + JSON.stringify(fileObj) + '\n\n');

jsonfile.writeFile(filePath, fileObj, function (err) {
    if (err) {
        console.error(err);
    }
});
}

Now you can use this function and call it as

writeToConfig(finalRandomName, config);
Gaurav Lad
  • 1,788
  • 1
  • 16
  • 30