Attempts to create a cron script to dump a MySQL database result in an empty file despite successful file saving. Log printing also yields an empty string.
The issue stems from several problems in the provided code:
The following code corrects these issues and provides a functioning solution:
var mysql_backup = function() { this.backup = ''; this.mysql = require('mysql'); this.init = function() { this.connection = this.mysql.createConnection({ user: 'root', password: 'root', database: 'test' }); // Connect to the database this.connection.connect(function(err) { if (err) console.log(err); db.get_tables(function() {}); }); }; this.query = function(sql, callback) { this.connection.query(sql, function (error, results, fields) { if (error) { throw error; } if (results.length > 0) { callback(results); } }); }; this.get_tables = function(callback){ var counter = 0; var me = this; this.query('SHOW TABLES', function(tables) { for (table in tables) { counter++; me.query('SHOW CREATE TABLE ' + tables[table].Tables_in_test, function(r){ for (t in r) { me.backup += "DROP TABLE " + r[t].Table + "\n\n"; me.backup += r[t]["Create Table"] + "\n\n"; } counter--; if (counter === 0) { me.save_backup(); me.connection.destroy(); } }); } }); }; this.save_backup = function() { var fs = require('fs'); fs.writeFile("./backup_test.txt", this.backup, function(err) { if(err) { console.log(err); } else { console.log("The file was saved!"); } }); } }; var db = new mysql_backup; db.init();
Consider using:
The above is the detailed content of Why is my MySQL database dump using Node.js resulting in an empty file despite successful file saving?. For more information, please follow other related articles on the PHP Chinese website!