Skip to content
Related Articles

Related Articles

Check if NodeJS MySQL Server is Active or not
  • Difficulty Level : Hard
  • Last Updated : 09 Feb, 2021

We will see how to check if the server where our MySQL Database is Hosted is Active or Not.

Syntax:

database_connection.ping(callback);

Modules:

  • NodeJS
  • ExpressJS
  • MySQL

    Setting environment and Execution:

  1. Create Project



    npm init

  2. Install Modules

    npm install express
    npm install mysql

    File Structure:

  3. Create Server

    index.js




    const express = require("express");
    const database = require('./sqlConnection');
      
    const app = express();
      
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });
  4. Create and export database connection object

    sqlConnection.js




    const mysql = require("mysql");
      
    let db_con  = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: ''
    });
      
    db_con.connect((err) => {
        if (err) {
          console.log("Database Connection Failed !!!", err);
        } else {
          console.log("connected to Database");
        }
    });
      
    module.exports = db_con;
  5. Create Route to Check mysql server Active or Not.




    app.get("/getMysqlStatus", (req, res) => {
      
      database.ping((err) => {
        if(err) return res.status(500).send("MySQL Server is Down");
          
        res.send("MySQL Server is Active");
      })
    });

    Full index.js File:

    Javascript




    const express = require("express");
    const database = require('./sqlConnection');
      
    const app = express();
      
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });
      
    app.get("/getMysqlStatus", (req, res) => {
          
        database.ping((err) => {
            if(err) return res.status(500).send("MySQL Server is Down");
              
            res.send("MySQL Server is Active");
        })
    });
  6. Run Server

    node index.js
  7. Output: Put this link in your browser http://localhost:5000/getMysqlStatus

    • If server is Not Active you will see below output in your browser:
    MySQL Server is Down

    • If server is Active you will see below output in your browser:
    MySQL Server is Active

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :