尝试创建 cron 脚本来转储 MySQL 数据库会导致空文件文件保存成功。日志打印也会产生一个空字符串。
该问题源于所提供代码中的几个问题:
以下代码纠正了这些问题并提供了一个有效的解决方案:
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();
为了清楚起见,考虑使用:
以上是尽管文件保存成功,但为什么使用 Node.js 的 MySQL 数据库转储会导致空文件?的详细内容。更多信息请关注PHP中文网其他相关文章!