title: How to stop a file from beign overwritten with fs.writefile
body: <p>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.</p>
  <p>This is what i tried at first:</p>
  <pre class="lang-js prettyprint-override"><code>socket.on('send-chat-message', message =&gt; {
  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(&quot;There has been an error saving your configuration data&quot;)
    console.log(error.message)
    return
    }
    console.log('Configuration saved succesfully')
    })
  })
  })
  </code></pre>
  
  <p>But that would just overwrite it. So then i tried like this:</p>
  <pre class="lang-js prettyprint-override"><code>socket.on('send-chat-message', message =&gt; {
  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(&quot;There has been an error saving your configuration data&quot;)
    console.log(error.message)
    return
    }
    console.log('Configuration saved succesfully')
    })
  })
  })
  </code></pre>
  
  <p>But then i get the error: 'ERR_INVALID_OPT_VALUE_ENCODING'</p>
  <p>So how could i fix this problem?</p>