Knowing What Node Closes for You

Your runJob() port now releases the job’s lock and deletes its spool copy in finally blocks. It acquires each resource on the line before its try. Before you turn every other with in Priya’s runner.py into a try/finally, it pays to ask which resources need cleanup code at all.

Python and JavaScript close different things for you, and Node keeps running while a timer or connection is still open. In this lesson, you’ll sort the runner’s resources, so you know where a finally belongs and why a program can keep running after its last line.

Let the Whole-File Functions Close Their Files

Most of the runner’s file work needs no cleanup code. Like Python’s Path.read_text(), Node’s whole-file functions open and close the file at the path you give them: readFile(), writeFile(), and copyFile() from node:fs/promises, and their synchronous forms in node:fs, such as copyFileSync(). The synchronous forms close it before they return, and the promise forms close it when their promise settles, so await them.

That covers the lock and the spool copy too: writeFileSync() has closed locks/J-311.lock before the next line, so the finally only deletes it with unlinkSync().

Reading the jobs is the same: Python’s json.loads(Path(path).read_text()) is the port’s JSON.parse(await readFile(path, "utf8")).

Close Every FileHandle You Open

Things change when you write a file piece by piece, adding each line as it’s ready instead of building the whole text first. For a short sheet, you could join the lines and make one writeFile() call, but a handle earns its keep when lines arrive over time or the output is too big to hold. Say the press operators want a job sheet with one line per job in jobs.json, which this lesson’s examples read:

Language: JSON Filename: 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" }
]

In Python, you’d open the sheet in a with block and write each line:

Language: Python
import json
from pathlib import Path

jobs = json.loads(Path("jobs.json").read_text())
with open("job-sheet.txt", "w") as sheet:
    for job in jobs:
        sheet.write(f"{job['id']} {job['art']} x {job['copies']}\n")

In JavaScript, open() from node:fs/promises is the counterpart of Python’s open(). The basic modes "r", "w", and "a" match, but Python’s "x" is Node’s "wx", as for the lock, and Node has no "b" or "t". Node’s open() returns a promise, and await gives you a FileHandle, an object that keeps the file open until you call its .close().

JavaScript’s closest match to with is await using, which a later lesson covers. Until then, the port opens the file on the line before try, as in the last lesson, and closes it in finally:

Language: JavaScript
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 whole-file writeFile(path, data) opens and closes the file itself, but the handle’s sheet.writeFile(data) writes through a handle you already opened and leaves closing it to you, hence the finally.

The handle’s writeFile() continues from the last write and, like Python’s write(), adds no newline. Unlike a FileHandle’s .write(), which can quietly write part of a line, writeFile() writes all of it or rejects. Both it and .close() return promises, so each gets an await. Reading the sheet back shows four lines, plus the blank line console.log() adds:

Language: Program Output
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 without closing. CPython closes a file object the moment nothing refers to it, though development mode flags it with a ResourceWarning. Node doesn’t. When the garbage collector finds a dropped FileHandle later, Node 26 closes it and raises an error that stops the program.

This loop opens jobs.json 20,000 times, piling up garbage so the collector runs early. It reads the file through each handle’s .readFile(), which, like sheet.writeFile(), leaves closing to you. The loop never closes a handle:

Language: JavaScript
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}`);
  }
}

On this run, it stopped before its first read line. Node also printed two blank lines after the first line, left out here:

The error text is wrapped for display.

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

Elsewhere, it may get further, show a different file descriptor, or run out of descriptors first, raising EMFILE. The fix is to close each handle in a finally, or better, to call readFile("jobs.json", "utf8"). When a program ends, the operating system closes whatever it left open, in both languages, so the risk is a program that stops partway, or one that won’t stop at all.

Close the Print Queue Before main() Ends

A dropped FileHandle eventually stops the program. An unclosed print queue never fails at all. It keeps the program running. In runner.py, PrinterQueue is an async context manager whose __aenter__() starts a heartbeat task, the real connection’s keep-alive:

Language: Python
import asyncio
import contextlib

class PrinterQueue:
    def __init__(self, press):
        self.press = press

    async def __aenter__(self):
        await asyncio.sleep(0.01)
        self.heartbeat = asyncio.create_task(self._beat())
        print(f"[queue] connected to {self.press}")
        return self

    async def _beat(self):
        while True:
            await asyncio.sleep(1)

    async def __aexit__(self, *exc_info):
        self.heartbeat.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self.heartbeat
        print(f"[queue] closed {self.press}")

Its send() sleeps and prints the line the press accepted.

In the JavaScript stand-in, the heartbeat is a timer. Where the global setTimeout() calls a function once after a delay, setInterval() calls it every 1,000 milliseconds until you pass the timer it returns to clearInterval().

The class starts one with setInterval(() => {}, 1000), whose empty arrow function stands in for the keep-alive message. Like Python’s task, it runs alongside your code, but only the class’s close() stops it.

To pause, the class imports a different setTimeout(), the one from node:timers/promises, as sleep(). It returns a promise that only waits, and the class awaits it like asyncio.sleep().

The class connects in a static method, called on the class itself, PrinterQueue.connect("press-1"), much like a Python @classmethod, though with no cls parameter. Inside it, this is the class, but the usual style names it: new PrinterQueue(press). Why it connects there comes up later. Save it as printer-queue.js:

Language: JavaScript Filename: 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, Node keeps a program running while a timer or connection is pending: an interval’s callback is still due every second, so there’s work left to do. This script sends the morning’s two printable jobs and leaves both queues open:

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

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

The whole runner does the same without its close() calls. It prints the full morning, down to Locks left: J-314.lock, and waits. If runner.py called __aenter__() and never __aexit__(), its heartbeat task would be left pending, yet the script would end at once: asyncio.run() cancels leftover tasks when main() returns. JavaScript has no such sweep, so close both queues in a finally, newest first:

Language: JavaScript
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");

Now both heartbeats are cleared, and the program ends after its last line:

Language: Program Output
[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
[queue] closed press-2
[queue] closed press-1
Done: 2 printed

The runner’s main() takes the same shape, inside the outer try/finally that removes the spool folder. Unlike nested async with blocks, though, it leaves press-1 open if the second connect() fails or press2.close() throws. Later lessons close that gap.

Let the whole-file functions close the files they open. Close every FileHandle and connection and clear every timer yourself, ideally 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 and writes the job’s proof through an open file handle. The function releases the lock and closes the handle however the writing ends, leaving another runner’s lock alone.

Become a Member to join the conversation.