Loading video player…

Porting with to try/finally

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.

Language: JavaScript
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.

Language: Program Output
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.

00:00 In this lesson, you’ll port Priya’s job lock from Python’s with to JavaScript’s try and finally, and see why a first port deleted the other PC’s lock.

00:10 Her run_job() wraps each job in a with JobLock block. Its __enter__() creates the lock file with exist_ok=False, and its __exit__() deletes it.

00:24 Watch out: 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.

00:35 So the port uses try and finally, which work as in Python: finally runs however the try ends. Your port starts as an empty runJob() function.

00:48 First, the lock’s path: join() builds it with the system’s separator, as a Path does. Then writeFileSync() from node:fs writes the lock file, empty, and finishes before the next line runs, as touch() does.

01:03 The "wx" flag writes only if the file doesn’t exist yet. Otherwise, it throws an error with the code EEXIST, the counterpart of exist_ok=False.

01:17 unlinkSync() deletes a file, like Python’s unlink(). A with block holds both steps, so the port puts both in one try: it takes the lock at the top and releases it in the finally.

01:31 Inside that try, the spool copy uses copyFileSync(), the counterpart of shutil.copy(). It copies the artwork from the art folder into the spool folder, named after the job, and then logs it.

01:45 That’s the order of Python’s spooled(): copy, then try.

01:51 Then an inner try sends the job to the press queue. Whatever happens there, its finally removes the copy, the way the finally in spooled() does in Python.

02:04 After both blocks, the done line comes last, as in Python. In main(), a catch handles each job’s errors, and finally blocks close the queues and remove the spool folder.

02:17 Here’s the intro’s run of your port, cut to its last nine lines. J-313’s artwork is missing, so that job failed. node:fs reports file errors as plain Errors, so the catch checks the code, ENOENT, where Python picks FileNotFoundError.

02:38 The error’s path is Python’s err.filename, with a backslash on Windows in both.

02:45 J-314 was skipped: EEXIST, Python’s FileExistsError. Unlike these excepts, a catch takes every error, so anything else is thrown again.

02:58 At the end, readdir() lists the locks as plain names: Locks left: none. But first, your runner released J-314.lock.

03:10 Back in Python, J-314’s lock already exists, so touch() raises inside __enter__(). Python goes straight to the skipped line, because a with statement only calls __exit__() once __enter__() has succeeded.

03:26 The other PC’s lock stays.

03:29 A finally, in JavaScript as in Python, runs whenever its try was entered. It was the with that checked __enter__() first.

03:40 For J-314, the try starts, and writeFileSync() throws EEXIST. The finally runs anyway, and unlinkSync() deletes the other PC’s lock.

03:51 The error reaches main(), which skips the job. And the next run would print J-314 a second time, while the other PC is still printing it.

04:02 The fix: move the two lock lines above the try, the shape spooled() already has: copy, then try. If writeFileSync() throws now, the try never starts, so its finally doesn’t run.

04:17 Put the other PC’s lock back, and run the morning again. J-314 shows only the skipped line, and the run ends with Locks left: J-314.lock, as Python’s does.

04:31 J-313’s artwork is missing, so its copyFileSync() throws. Your turn: pause the video and predict which of the two finally blocks run for J-313.

04:48 Only the lock’s. The copy failed before the inner try started, so nothing tries to delete a copy that was never made. J-313 prints took, released and failed, as in Python.

05:04 That’s the JavaScript way: take each resource right before its try, with one try and finally per resource, nested as your with blocks are, and released in reverse order.

05:16 The finally then only releases what you hold. Next up, Knowing What Node Closes for You, a text lesson: which file calls clean up after themselves, and which resources need closing.

Become a Member to join the conversation.