Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs write json to a file

Tags:

json

node.js

I just started learning nodejs. I am currently working with sockets and made chat program.

I want to save entire chat to a json file. Currently my code is this :

  socket.on('chat', function  (data) {
    message = {user : data.message.user, message : data.message.message};
    chat_room.sockets.emit('chat', {message: message});

    jsonString = JSON.stringify(message);

    fs.appendFile("public/chat.json", jsonString, function(err) {
        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved!");
        }
    }); 

  });

This is currently working perfect, but the json which is written in file is wrong.

This gave me a wrong json

{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}

The above code is called when message is triggered. I want json in this format

{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}

Can anyone help me in this? Thanks in advance

like image 479
Niraj Chauhan Avatar asked Nov 25 '12 15:11

Niraj Chauhan


1 Answers

The first set of wrong JSON is created because you are appending a piece of JSON to a file each time you get a message.

The second set of JSON is also wrong - each property name has to be unique.

Presumably you want something like:

[
{"user":"niraj","message":"hw r u?"},
{"user":"ntechi","message":"hello"},
{"user":"ntechi","message":"hw r u?"}
]

In which case the logic you need to use is:

  1. Read data from file
  2. Parse data as JSON and assign to a variable
  3. In the event of an error, assign an empty array to that variable
  4. push the message object onto the end of the array
  5. stringify the array
  6. Overwrite the file with the new string
like image 116
Quentin Avatar answered Sep 22 '22 20:09

Quentin