I just started learning nodejs. I am currently working with sockets and made chat program.
我刚开始学nodejs。我目前正在使用socket和做聊天程序。
I want to save entire chat to a json file. Currently my code is this :
我想把整个聊天保存到一个json文件。目前我的代码是:
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.
这目前运行良好,但是在文件中写入的json是错误的。
This gave me a wrong json
这给了我一个错误的json
{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}
{“用户”:“niraj”、“消息”:“hw r u ?”} {“用户”:“ntechi”、“消息”:“你好”} {“用户”:“ntechi”、“消息”:“hw r u ?”}
The above code is called when message is triggered. I want json in this format
当消息被触发时,将调用上面的代码。我想要json格式
{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}
{“用户”:“awd”、“消息”:“hw r u ?”“用户”:“ntechi”、“信息”:“你好”,“用户”:“ntechi”、“消息”:“hw r u ?”}
Can anyone help me in this? Thanks in advance
有人能帮我吗?谢谢提前
1 个解决方案
#1
11
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.
第一个错误的JSON集被创建,因为每次收到消息时,您都要向文件中添加一块JSON。
The second set of JSON is also wrong - each property name has to be unique.
第二组JSON也是错误的——每个属性名都必须是唯一的。
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:
在这种情况下,您需要使用的逻辑是:
- Read data from file
- 从文件读取数据
- Parse data as JSON and assign to a variable
- 将数据解析为JSON并分配给变量
- In the event of an error, assign an empty array to that variable
- 在发生错误时,为该变量分配一个空数组
-
push
the message object onto the end of the array - 将消息对象推到数组的末尾。
- stringify the array
- stringify数组
- Overwrite the file with the new string
- 用新字符串覆盖文件
#1
11
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.
第一个错误的JSON集被创建,因为每次收到消息时,您都要向文件中添加一块JSON。
The second set of JSON is also wrong - each property name has to be unique.
第二组JSON也是错误的——每个属性名都必须是唯一的。
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:
在这种情况下,您需要使用的逻辑是:
- Read data from file
- 从文件读取数据
- Parse data as JSON and assign to a variable
- 将数据解析为JSON并分配给变量
- In the event of an error, assign an empty array to that variable
- 在发生错误时,为该变量分配一个空数组
-
push
the message object onto the end of the array - 将消息对象推到数组的末尾。
- stringify the array
- stringify数组
- Overwrite the file with the new string
- 用新字符串覆盖文件