This Node.js script allows you to easily back up MySQL databases using the mysqldump package. Connection credentials and the backup path are managed securely via a .env file.
- Backup one or multiple MySQL databases.
- Export
.sqlfiles to a specified path. - Use environment variables for secure and flexible configuration.
- Node.js installed on your machine.
- MySQL/MariaDB accessible from your machine.
- Appropriate permissions to connect to the database and perform a dump.
- Clone this repository or download the script files.
- Install the required dependencies:
npm install
-
Create a .env file in the project root by copying the provided env.sample file:
cp .env.sample .env
-
Edit the .env file with your MySQL database credentials and backup path:
DB_HOST=localhost DB_PORT=3306 DB_USER=root DB_PASSWORD= BACKUP_PATH=./- DB_HOST: Your MySQL server address (default is localhost).
- DB_PORT: MySQL server port (default is 3306).
- DB_USER: MySQL user.
- DB_PASSWORD: MySQL user password.
- BACKUP_PATH: The directory where backup files will be stored (ensure this path exists).
-
Update the
dbarray in the index.js file to include the databases you want to backup.const db = [ { dbName: 'example_db1' }, { dbName: 'example_db2' }, ];
-
Run the script:
npm run dump
- Alternative: Run the
dbDump.batfile
- Alternative: Run the
-
The backup files will be saved in the specified
BACKUP_PATHwith names likebackup_<database_name>.sql.
To automate the backup every day, you can use the Windows Task Scheduler.
- Open the Windows Start menu and search for Task Scheduler.
- In Task Scheduler, click on Create Task (on the right-hand side).
- In the General tab:
- Enter a name for your task (e.g., MySQL Daily Backup).
- Select the option Run whether user is logged on or not.
- Check Run with highest privileges.
- In the Triggers tab:
- Click New....
- Set Begin the task to On a schedule.
- Select Daily and set the time you want the backup to run.
- Click OK.
- In the Actions tab:
- Click New....
- Set Action to Start a program.
- In the Program/script field, browse to your backup.bat file.
- Click OK.
- In the Conditions tab:
- Uncheck Start the task only if the computer is on AC power (if you want backups to run on laptops even when on battery).
- Click OK to save the task.
- You will be prompted to enter your Windows user credentials for authentication.
- In Task Scheduler, locate your task.
- Right-click on it and choose Run.
- Check your backup folder to ensure the backup files are created successfully.
```
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
BACKUP_PATH=./
```
- If the script encounters an error, it will log the error message and exit.
- Ensure the
BACKUP_PATHdirectory exists and is writable. - Check your MySQL credentials and permissions.
This project is licensed under the MIT License.