Handling a Missing File

Early in December, Joan types november.csv before she’s downloaded November’s export. The Python script donations.py catches that with except FileNotFoundError and calls sys.exit(f"No such file: {path}"), so instead of a traceback, she gets one line and an error exit. The JavaScript port should be as polite, but Node has no FileNotFoundError to catch.

Check the Code Instead of a Class

For a missing file, awaiting readFile() throws a plain Error, so err.name is "Error".

Python builds its OSError subclasses on error numbers named ENOENT, EISDIR, and so on. Node skips the subclasses and passes that name straight through as the error’s code property. A missing file, or a missing folder on its path, gets "ENOENT", short for “error, no entry.” You’d write the same check in Python as err.errno == errno.ENOENT, except that Node hands you the name as a string.

So the catch block tests the code, with the expected case first and else { throw err; } last. This scratch script in the donations/ folder tries it:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.