Here's a function I use to generate a 2.5 gig SQL dump file for testing. It works but it takes a long time. How can I make it more efficient?
const crypto = require("crypto");
const fs = require('fs');
const os = require('os');
const path = require('path');
(async function main(){
var dumpfile = await generate_large_dump();
console.log("\nDump created: ", dumpfile);
})();
function generate_large_dump(){
return new Promise(async (resolve, reject)=>{
var total_bytes = 0;
const target_bytes = 2.5 * 1e+9;
const target_file = path.join(os.tmpdir(), 'large_dump.sql');
const writerStream = fs.createWriteStream(target_file, {flags: 'w'});
writerStream.on('error', console.error);
const age = ()=>Math.floor(Math.random() * (95 - 18 + 1)) + 18;
const name = ()=>crypto.randomBytes(16).toString("hex");
const write = str => new Promise(resolve=>{
total_bytes += Buffer.byteLength(str, 'utf8');
writerStream.write(str, resolve);
var pct = Math.min(100, Math.floor(total_bytes / target_bytes * 10000)/100);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(pct+"% complete");
});
var create_sql = "CREATE TABLE `sample_table` (`id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(250) NOT NULL, `age` int(11) NOT NULL, `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`));\n";
await write(create_sql);
while(total_bytes < target_bytes) await write("INSERT INTO `sampe_table` (`name`, `age`) VALUES ('"+name()+"', '"+age()+"');\n");
writerStream.end();
process.stdout.write("\n");
resolve(target_file);
});
}