Porting with to try/finally
JavaScript’s with keyword isn’t a cleanup statement: it’s an old statement for looking up
names on an object, and a SyntaxError in a module. (using, later in the course, comes
closer.) The first port of with JobLock(job["id"]): is try/finally, which works as in Python: the finally
block runs however the try block ends.
The lock’s two calls come from node:fs. writeFileSync(lockPath, "", { flag: "wx" }) writes
an empty file, and the "wx" flag makes it throw an error with the code "EEXIST" if the file
already exists, as exist_ok=False does. unlinkSync(lockPath) deletes it, like unlink().
The spool copy is copyFileSync(), the counterpart of shutil.copy(), with a try/finally
of its own.
Watch where the acquiring line goes. Python’s with only calls __exit__() once __enter__()
has succeeded, but a finally, in JavaScript as in Python, runs whenever its try was entered.
With writeFileSync() inside the try, J-314’s finally deleted the other PC’s lock, and the
run ended Locks left: none. Take the lock right before the try, the shape Priya’s spooled()
already has (copy, then try), so the finally only releases what you hold.
Here’s the port, with one try/finally per resource, nested as the with blocks are and
released in reverse order: the spool copy, then the lock.
async function runJob(job, queue, folder) {
const lockPath = join(LOCKS, `${job.id}.lock`);
writeFileSync(lockPath, "", { flag: "wx" });
console.log(` [lock] took ${job.id}.lock`);
try {
const spool = join(folder, `${job.id}.pdf`);
copyFileSync(join(ART, job.art), spool);
console.log(` [spool] wrote ${job.id}.pdf`);
try {
await queue.send(spool, job.copies);
} finally {
unlinkSync(spool);
console.log(` [spool] removed ${job.id}.pdf`);
}
} finally {
unlinkSync(lockPath);
console.log(` [lock] released ${job.id}.lock`);
}
console.log(` done: ${job.id} for ${job.customer}`);
}
When J-313’s copyFileSync() throws, only the lock’s finally runs, because the inner try
never started.
In main(), the catch around each job checks err.code, since node:fs reports file errors as
plain Errors: "EEXIST" means another runner holds the lock, and "ENOENT" means the artwork is
missing, with err.path naming the file as err.filename does (art\flyers.pdf on Windows, in
both languages). Any other error is thrown again, because a catch takes every error, where except names its
classes, and readdir() lists the locks left at the end.
With the other PC’s lock back, the morning now ends as Python’s does.
J-314 on press-2
skipped: J-314 is locked by another runner
[queue] closed press-2
[queue] closed press-1
[spool] removed the spool folder
Done: 2 printed, 1 failed, 1 skipped
Locks left: J-314.lock
Next up, Knowing What Node Closes for You: which file calls clean up after themselves, and which resources need closing.