A Question About Net Module For Handling Messages in the Back-end

28 views Asked by At

In Node.js, I designed my own custom protocol for handling messages using net module; however, I'm not sure whether this code saves the messages to the database real-time or not. That is, I want to learn if this code works real-time or not. Here's the entire code:

const net = require("net");
 const mysql = require("mysql2");

 const server = net.createServer(socket => {
    socket.on("data", data => {
          db.query("INSERT INTO messages (message) VALUES (?)", [data.toString()], (e, r) => {
        if (!e) {
            console.log("Saved the message successfully!");
        }

        else {
            throw e;
        }
      });
    });
});

 server.listen(3000, "127.0.0.1", () => {
    console.log("Connected to the server successfully!");
});

 const db = mysql.createConnection({
    host: "127.0.0.1",
    port: 3306,
    user: "root",
    password: "",
    database: "message"
});

 db.connect(err => {
    if (!err) {
        console.log("Connected to the database successfully!");
    }

    else {
        throw err;
    }
});

I couldn't be sure about whether this code is real-time or not. I want to save the messages to the database real-time, not asynchronously.

0

There are 0 answers