Open In App

Check if Node.js MySQL Server is Active or not

Last Updated : 07 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads