Porting the Backup Check
In this lesson, you ported the sysadmin’s Python check to JavaScript, line by line, keeping its logic and changing its declarations and types. Then you ran both versions three ways and compared their output and exit status.
- In Node,
process.envplays the part ofos.environ, and it needs no import. You read each setting as a property, with a dot, not with aget()call. An unset variable isundefined, notNone, and every set one is a string. - Each read becomes a declaration with a camelCase name. A setting the check never changes is a
const. The region is reassigned further down, when its default is filled in, so it’s alet. - The flag compares with
=== "1", sodryRunholdstrueorfalse.DRY_RUN=falseis the text"false", which isn’t"1", so the check runs live. - The placeholder
lastSuccessis alet, because the job reassigns it when a backup finishes, and it starts asnull, where Python usesNone. - Reading
process.env.BACKUP_RETRIESis a plain property read, with nowhere to pass a default the way you pass one toos.environ.get(). So the port fills in the retry count’s default of"3"the way it fills in the region’s, then converts the text once withNumber(retriesText). Without the conversion,retries + 1would join text and promise 51 attempts. - Unlike
int(),Number()never raises: it givesNaNfor text that isn’t a number, such as"abc". The port doesn’t check for that, so it runs on and exits with status 0, where Python’sint()stops the check with status 1. is Nonebecomes=== undefined. A=== nullcheck would wave an unset bucket through.sys.exit(1)becomesprocess.exit(1), which ends the program with an exit code, assys.exit()does. An exit code of 0 means success and anything else means failure, which is what cron checks, so cron sees the failure.- The mode is declared with
let mode;before itsif/else, so the print lines can reach it. Aconstinside each branch would end at its closing brace. node --check backup-check.jsreads the whole file without running it, and prints nothing when there’s no syntax error, such as a secondletfor the same name.
Here’s the port, backup-check.js, without the warning and the debug line:
const bucket = process.env.BACKUP_BUCKET;
let region = process.env.BACKUP_REGION;
const notifyEmail = process.env.NOTIFY_EMAIL;
const dryRun = process.env.DRY_RUN === "1";
let retriesText = process.env.BACKUP_RETRIES;
if (retriesText === undefined) {
retriesText = "3";
}
const retries = Number(retriesText);
let lastSuccess = null;
if (bucket === undefined) {
console.log("No BACKUP_BUCKET set: refusing to start.");
process.exit(1);
}
if (region === undefined) {
region = "eu-west-1";
}
let mode;
if (dryRun) {
mode = "dry run";
} else {
mode = "live";
}
console.log(`Backing up to ${bucket} in ${region} (${mode})`);
console.log(`Up to ${retries + 1} attempts`);