The problem is that when I am trying to save data that I get from a chat room that is made with socket.io in nodejs, the file keeps getting overwritten once the user has submitted their message to the chatroom. However I want the user name + message to be added to the file instead of overwriting it, so both the username and the message will get stored in to the JSON file as a object.
This is what i tried at first:
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message',{ message: message, name: users[socket.id] })
var collect = {
message: message,
name: users[socket.id]
}
var savechatData = JSON.stringify(collect)
fs.writeFile('./public/static/chattingdata/chat.json', savechatData, function (error) {
if (error) {
console.log("There has been an error saving your configuration data")
console.log(error.message)
return
}
console.log('Configuration saved succesfully')
})
})
})
But that would just overwrite it. So then i tried like this:
socket.on('send-chat-message', message => {
socket.broadcast.emit('chat-message',{ message: message, name: users[socket.id] })
var collect = {
message: message,
name: users[socket.id]
}
var savechatData = JSON.stringify(collect)
fs.writeFile('./public/static/chattingdata/chat.json', {'flags': 'a'}, savechatData, function (error) {
if (error) {
console.log("There has been an error saving your configuration data")
console.log(error.message)
return
}
console.log('Configuration saved succesfully')
})
})
})
But then i get the error: 'ERR_INVALID_OPT_VALUE_ENCODING'
So how could i fix this problem?