Check if Node.js MySQL Server is Active or Not
Last Updated :
03 Jul, 2024
To check if a MySQL server is active or not from a Node.js application, you typically want to establish a connection to the MySQL server and handle any errors that occur during the connection attempt. Here’s a step-by-step guide on how to achieve this.
Prerequisites:
Approach
To check if a Node.js MySQL server is active, use the mysql
package to create a connection and call database_connection.ping(callback)
to verify the server status in the callback function.
Syntax:
database_connection.ping(callback);
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the required dependencies by the following command:
npm install express
npm install mysql
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.15.4",
"mysql": "^2.18.1",
}
Example: Implementation to create server first and also create and export database connection object.
Node
// 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;
Node
// app.js
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) => {
// Create Route to Check mysql server Active or Not.
database.ping((err) => {
if(err) return res.status(500).send("MySQL Server is Down");
res.send("MySQL Server is Active");
})
});
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.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

MySQL Server is Active

If server is Active you will see below output in your browser:
Additional Considerations
- Error Handling: Always handle connection errors to gracefully manage server unavailability or configuration issues.
- Connection Pooling: For production applications, consider using connection pooling (
mysql2
supports this) to efficiently manage database connections. - Environment Variables: Store sensitive database credentials (like passwords) in environment variables and access them securely in your Node.js application.
- Monitoring: Implement health checks or monitoring solutions to continuously monitor the status of your MySQL server.
Conclusion
Checking if a MySQL server is active from a Node.js application involves establishing a connection and handling connection errors. By following the steps outlined above and using appropriate error handling techniques, you can ensure that your application can reliably connect to and interact with MySQL databases.
Similar Reads
How to Connect Node.js Application to MySQL ?
To connect the Node App to the MySQL database we can utilize the mysql package from Node Package Manager. This module provides pre-defined methods to create connections, query execution and perform other database related operations. Approach to Connect Node App to MySQLFirst, initialize the node.js
2 min read
How to check whether a script is running under Node.js or not ?
In JavaScript, there is not any specific function or method to get the environment on which the script is running. But we can make some checks to identify whether a script is running on Node.js or in the browser. Using process class in Node.js: Each Node.js process has a set of built-in functionalit
3 min read
Node.js MySQL Order By Clause
Introduction: We use the SQL ORDER BY Clause to sort the data with respect to some column value in ascending or descending order. Syntax: SELECT * FROM users ORDER BY name; This will sort all rows of output in ascending order (by default) with respect to name column. SELECT address FROM users ORDER
2 min read
How to Use Connection Pooling with MySQL in Node.js?
MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
3 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications.In this article, we'll explore how to connect a Node.js application with a MySQL database, coveri
2 min read
How to use .env file in NodeJS MySQL?
Environment variables are list of properties defined by key and value used for storing configurations data for instance the database credentials, api keys and so on. In the past, these values were directly coded into your applicationsâ code and were not flexible to change, but today we can store the
4 min read
Node.js MySQL FIND_IN_SET() Function
FIND_IN_SET() function is a built-in function in MySQL that is used to get the position of the first occurrence of value string in a list of strings separated by comma(','). Syntax: FIND_IN_SET(value, list_of_string)Parameters: It takes two parameters as follows: value: It is the value to be searche
2 min read
Node.js MySQL OR Operator
NodeJs: An open-source platform for executing javascript code on the server-side. Also, a javascript runtime built on Chromeâs V8 JavaScript engine. It can be downloaded from here. Mysql An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the
2 min read
Node.js MySQL Create Table
Introduction: Learn to create a table in MySQL database using NodeJS. We will see how to use the Create Table command in NodeJS using the MySQL module. Prerequisite: Introduction to NodeJS MySQL Setting up environment and Execution: Step 1: Create a NodeJS Project and initialize it using the followi
2 min read
How to Create and Use Stored Procedures in MySQL with Node.js?
Stored procedures in MySQL are very useful in the following ways Regarding the encapsulation of business logic within a database. They can be run multiple times and do not cause a large load on the client-server connection. In this tutorial, we will learn how to create and use stored procedures in M
3 min read