0

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?

RobC
  • 22,977
  • 20
  • 73
  • 80
SpringerJerry
  • 178
  • 1
  • 8

1 Answers1

1

fs.writeFile function's signature is fs.writeFile(file, data[, options], callback). The data parameter should be given as the second parameter and the optional options parameter as the third parameter. Refer Docs here

Change your code from

fs.writeFile('./public/static/chattingdata/chat.json', {'flags': 'a'}, savechatData, function (error){ // Callback })

to

fs.writeFile('./public/static/chattingdata/chat.json', savechatData, {'flags': 'a'}, function (error) { // callback })
Kishore Sampath
  • 973
  • 6
  • 13
  • This works but it still seems to overwrite the file. I have found that people said i have to use the flag a+ but this also overwrites the file. Which i dont want, because i want to add a new line to the file and not overwrite it. – SpringerJerry Apr 16 '21 at 13:18
  • 1
    @SpringerJerry Check this [solution](https://stackoverflow.com/questions/36093042/how-do-i-add-to-an-existing-json-file-in-node-js). They have asked to open the file first using `json.parse()`, then append the data to the file and lastly save the file again. – Kishore Sampath Apr 16 '21 at 13:40