Your runJob() port now takes the job’s lock before its try and releases it in the finally. Before you turn every other with in Priya’s runner.py into a try/finally, sort the runner’s resources, because Python and JavaScript don’t close the same things for you, and Node keeps running while a timer or connection is open.
Let the Whole-File Functions Close Their Files
Like Python’s Path.read_text(), Node’s whole-file functions open and close the file themselves. The promise forms from node:fs/promises close it when their promise settles, so await them, and the Sync forms from node:fs close it before they return. Only the last row here needs cleanup code:
| Python | JavaScript | Cleanup code |
|---|---|---|
Path(path).read_text() |
await readFile(path, "utf8") |
None |
Path(path).write_text(text) |
await writeFile(path, text) |
None |
shutil.copy(source, target) |
copyFileSync(source, target) |
None |
open(path, "w") |
await open(path, "w") |
await handle.close() |
The lock needs no close() either. writeFileSync() has closed locks/J-311.lock by the next line, so the lock’s finally only deletes the file.
Close Every FileHandle You Open
A handle earns its keep when you write a file piece by piece. Say the press operators want a job sheet with one line per job in jobs.json:
jobs.json
[
{ "id": "J-311", "customer": "Hartley's Bakery",
"art": "menus.pdf", "copies": 40, "press": "press-1" },
{ "id": "J-312", "customer": "St Anne's Primary",
"art": "newsletter.pdf", "copies": 120, "press": "press-2" },
{ "id": "J-313", "customer": "Moss & Fern",
"art": "flyers.pdf", "copies": 500, "press": "press-1" },
{ "id": "J-314", "customer": "Calder Rowing Club",
"art": "tickets.pdf", "copies": 200, "press": "press-2" }
]
Python would write each line inside with open("job-sheet.txt", "w") as sheet:. JavaScript’s counterpart is open() from node:fs/promises, with the same "r", "w", and "a" modes, "wx" for Python’s "x", and no "b" or "t". Awaiting it gives you a FileHandle, which keeps the file open until you call its .close().
JavaScript’s closest match to with comes later in the course. Until then, open the file on the line before try, as you took the lock, and close it in finally:
import { open, readFile } from "node:fs/promises";
const jobs = JSON.parse(await readFile("jobs.json", "utf8"));
const sheet = await open("job-sheet.txt", "w");
try {
for (const job of jobs) {
await sheet.writeFile(`${job.id} ${job.art} x ${job.copies}\n`);
}
} finally {
await sheet.close();
}
console.log(await readFile("job-sheet.txt", "utf8"));
The handle’s .writeFile() and .readFile() work like Python’s f.write() and f.read() on a file you opened, but return promises. Unlike the whole-file writeFile(path, text) and readFile(path), they leave closing it to you. .writeFile() continues from the last write and adds no newline, and unlike .write(), which can write only part of its input without an error, it writes all of it or rejects. .close() returns a promise too, so await each call.
Reading the sheet back shows four lines, plus the blank line console.log() adds:
J-311 menus.pdf x 40
J-312 newsletter.pdf x 120
J-313 flyers.pdf x 500
J-314 tickets.pdf x 200
Watch out for a handle you drop. CPython usually closes a dropped file object straight away, with a ResourceWarning that stays hidden unless you turn it on, for example, with -X dev. Node doesn’t: when the garbage collector finds an open FileHandle, Node 26 closes it and stops the program. This loop opens jobs.json 20,000 times, and handle.readFile() leaves each handle open, so garbage piles up and the collector runs early:
import { open } from "node:fs/promises";
for (let i = 1; i <= 20000; i++) {
const handle = await open("jobs.json");
await handle.readFile("utf8");
if (i % 1000 === 0) {
console.log(`read ${i}`);
}
}
The loop stopped before its first read line. The output below omits the two blank lines Node also printed after the first line:
The error text is wrapped for display.
<anonymous_script>:0
[Error: A FileHandle object was closed during garbage collection. This used to be
allowed with a deprecation warning but is now considered an error. Please close
FileHandle objects explicitly. File descriptor: 20 (jobs.json)] {
code: 'ERR_INVALID_STATE'
}
Node.js v26.13.1
Another machine may get further, show another descriptor, or hit the too many open files error, EMFILE, first. Close each handle in a finally, or better, call readFile("jobs.json", "utf8"). When a program ends, the operating system closes whatever it left open, in both languages.
Close the Print Queue Before main() Ends
Where a dropped handle stops the program, an unclosed print queue keeps it running. In runner.py, the __aenter__() method of PrinterQueue starts a heartbeat task, the real connection’s keep-alive, and __aexit__() cancels it. The JavaScript stand-in uses a timer:
| Python | JavaScript |
|---|---|
async with PrinterQueue("press-1") as press_1: |
const press1 = await PrinterQueue.connect("press-1"); |
asyncio.create_task(self._beat()) |
setInterval(() => {}, 1000) |
self.heartbeat.cancel() in __aexit__() |
clearInterval(this.heartbeat) in close() |
await asyncio.sleep(0.01) |
await sleep(10) |
Where the global setTimeout() calls a function once, setInterval() calls it every 1,000 milliseconds until you pass its timer to clearInterval(). The empty arrow function stands in for the keep-alive message, and sleep() is the promise-based version of setTimeout() from node:timers/promises.
connect() is a static method, called on the class like a Python @classmethod with no cls parameter. When you call PrinterQueue.connect(), this inside the method is the class, but you usually write the class name instead, as in new PrinterQueue(press). Why the connecting happens there comes up later. Save the class as printer-queue.js:
printer-queue.js
import { setTimeout as sleep } from "node:timers/promises";
export class PrinterQueue {
constructor(press) {
this.press = press;
this.heartbeat = setInterval(() => {}, 1000);
}
static async connect(press) {
await sleep(10);
const queue = new PrinterQueue(press);
console.log(`[queue] connected to ${press}`);
return queue;
}
async send(spool, copies) {
await sleep(10);
console.log(` [queue] ${this.press} accepted ${spool} x ${copies}`);
}
async close() {
clearInterval(this.heartbeat);
await sleep(10);
console.log(`[queue] closed ${this.press}`);
}
}
Watch out for a queue you never close. By default, an interval keeps Node running because it’s always due again. This script sends two jobs and leaves both queues open:
import { PrinterQueue } from "./printer-queue.js";
const press1 = await PrinterQueue.connect("press-1");
const press2 = await PrinterQueue.connect("press-2");
await press1.send("J-311.pdf", 40);
await press2.send("J-312.pdf", 120);
console.log("Done: 2 printed");
Every line prints, and then the program sits with no prompt until you press Ctrl+C:
[queue] connected to press-1
[queue] connected to press-2
[queue] press-1 accepted J-311.pdf x 40
[queue] press-2 accepted J-312.pdf x 120
Done: 2 printed
Without its close() calls, the whole runner prints everything through Locks left: J-314.lock and waits the same way. Python ends at once, because asyncio.run() cancels leftover tasks when main() returns. JavaScript has no such sweep, so close both queues in a finally, newest first:
import { PrinterQueue } from "./printer-queue.js";
const press1 = await PrinterQueue.connect("press-1");
const press2 = await PrinterQueue.connect("press-2");
try {
await press1.send("J-311.pdf", 40);
await press2.send("J-312.pdf", 120);
} finally {
await press2.close();
await press1.close();
}
console.log("Done: 2 printed");
The script prints [queue] closed press-2 and [queue] closed press-1 before Done: 2 printed, and with both heartbeats cleared, the program ends.
The runner’s main() takes this shape inside the outer try/finally that removes the spool folder. Unlike nested async with blocks, it leaves press-1 open if the second connect() fails or press2.close() throws, a gap later lessons close.
Let the whole-file functions close their own files. Close every FileHandle yourself, since Node stops the program when the garbage collector finds one open. Close every connection and clear every timer, since Node waits for them. Ideally, put this cleanup in the close() method of the object that created the resource.
Before a big job prints, the runner writes a proof sheet for the customer to approve. In the next exercise, Write the Proof Sheet Safely, you’ll write the function that takes the proofs folder’s lock, writes the job’s proof through an open file handle, and releases both however the writing ends. Another runner’s lock stays put, so the caller can report that proofs are being made elsewhere.