1

I'm new to Node.js and have written an chat in Node.js trough socket.io. It works well.

But what disturbs me is, when i reload the page, the whole chat data is gone. The chat box is clear.

How i can save all the data? Is it possible without logging anything?

aarivex
  • 35
  • 1
  • 6
  • 1
    Socket.io is simply a socket library, with no storage. You could hook it up to a database, such as Redis, MongoDB, MySQL, or any of the like. You'll need to log it in some form, since the socket broadcasts are ephemeral. You could always write to a flat file if you don't really care about speed/scalability. However, if you want past lines of chat, you'll need some sort of storage for it. If you just want a little context, you could keep a file that's got the last x lines of text, and pop off the oldest line when you add a new one. However, the best solution is to hook up some sort of datastore – Brandon Anzaldi Jan 04 '16 at 21:38

1 Answers1

2

What your looking for is a database. Don't think that this just means a MySQL database, as it also includes XML files, text files, JSON files, and a lot more.

To start off, take @Brandon's advice and learn how to append each chat message into the file. When your page reloads, iterate over each line of text or data entry and add it to the chat program.

Here's some helpful links:

How to append to a file in Node?

How to update a value in a json file and save it through node.js

How to parse JSON using Node.js?

https://docs.mongodb.org/getting-started/node/

Community
  • 1
  • 1
Alex L
  • 470
  • 6
  • 15