Check if Node.js MySQL Server is Active or not
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:
Setting environment and Execution:
-
Create Project
npm init
-
Install Modules
npm install express
npm install mysql
File Structure:
-
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 ...`);
});
|
-
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;
|
-
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" );
})
});
|
-
Run Server
node index.js
-
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
Last Updated :
07 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...