Your port now sorts October’s rows into good ones and rejected ones, and you know how to write a catch that lets anything unexpected through. One part of donations.py hasn’t moved yet: the file itself. Early in December, Joan types november.csv before she’s downloaded November’s export, and the Python script answers with one line, No such file: november.csv, instead of a traceback.
The JavaScript port should be as polite. In this lesson, you’ll find out what JavaScript throws for a missing file, check for it the way Node expects, and map the rest of Python’s familiar exceptions to JavaScript’s.
Find Out What a Missing File Throws
In Python, the except line picks the error by its class. Stripped down to the read, the try in donations.py looks like this:
import sys
path = "november.csv"
try:
with open(path, encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
sys.exit(f"No such file: {path}")
First, find out what JavaScript throws instead. This scratch script in the donations/ folder reads the export with readFile(), which opens, reads, and closes the file in one awaited call. Its catch only prints whatever it receives:
november.js
import { readFile } from "node:fs/promises";
try {
await readFile("november.csv", "utf8");
} catch (err) {
console.error(err);
}