-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackupDatabase.js
47 lines (46 loc) · 1.52 KB
/
backupDatabase.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* ## backupDatabase.js
* ### Create local backup of database specified under _pool_ key in env.json.
*
* Can be invoked directly with
* ```
* node backupDatabase.js [location]
* ```
* Or from within the project via the npm script
* ```
* npm run backup-database [location]
* ```
*
* By default, the backup is written to a new file `/path/testdata_TIMESTAMP.sql`, where the value
* of `/path/testdata.sql` is read from the _testDataPath_ key in env.json.
*
* The optional argument _loacation_ may be supplied to specify a different target path for the backup.
*/
const fs = require('fs');
const path = require('path');
const {pool, testDataPath} = require('./env.json');
const backupFile = path.resolve(
process.argv[2] || // backup file can be specified as an argument
testDataPath.replace(
// defaults to new timestamped file
/(\.[^.]*)?$/i, // match file extension (potentially absent)
`_${new Date().toISOString().replace(/[:.]/g, '_')}$1` // $1 expands to matched extension
)
);
require('child_process').exec(
`mysqldump -R -u ${pool.user} -p ${pool.database}`,
(error, stdout, stderr) => {
console.log(`Attempting to backup database ${pool.database}`);
if (error) throw error;
fs.writeFile(
backupFile,
stdout,
{flag: process.argv[2] ? 'w+' : 'wx+'}, // don't overwrite existing files unless explicitly instructed
(error) => {
if (error) throw error;
console.log('Backup written to');
console.log(backupFile);
}
);
}
);