Handle a file not found error in TypeScript
4 Handle a missing file
fairTry to open a file that is not there and handle the not-found failure with a clear message. Adapted: there is no file system in a browser, so this uses an in-memory store that fails the same way, with the real Node code shown alongside.
Stuck? Three hints, smallest first
- 1. Node throws an error carrying a
codeproperty; for a missing file it is'ENOENT'. - 2. Match on that code, not on the message text, because messages change between versions.
- 3. Model it with a custom error that also carries a
code, so the handling logic is identical.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// The real thing, for reference. It cannot run here:
//
// import { readFileSync } from 'node:fs';
// try {
// const text = readFileSync('missing.txt', 'utf8');
// } catch (err) {
// if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') { ... }
// }
//
// The stand-in below fails in the same shape: an Error with a .code of ENOENT.
class FileError extends Error {
constructor(message: string, public readonly code: string, public readonly path: string) {
super(message);
this.name = 'FileError';
}
}
const DISK = new Map<string, string>([
['manifest.txt', 'LAG-441-XA\nABJ-772-KM'],
['empty.txt', ''],
]);
function readFileSync(path: string): string {
const found = DISK.get(path);
if (found === undefined) {
throw new FileError(`no such file or directory, open '${path}'`, 'ENOENT', path);
}
return found;
}
function readOrExplain(path: string): string {
try {
const text = readFileSync(path);
return text === '' ? `${path} is empty` : `${path}: ${text.split('\n').length} line(s)`;
} catch (err) {
// Match the code, not the wording of the message.
if (err instanceof FileError && err.code === 'ENOENT') {
return `${path} was not found`;
}
throw err;
}
}
console.log(readOrExplain('manifest.txt'));
console.log(readOrExplain('empty.txt'));
console.log(readOrExplain('missing.txt'));
test('an existing file is read', readOrExplain('manifest.txt'), 'manifest.txt: 2 line(s)');
test('an empty file is not the same as a missing one', readOrExplain('empty.txt'), 'empty.txt is empty');
test('a missing file is reported', readOrExplain('missing.txt'), 'missing.txt was not found');
test('the error carries a machine-readable code', (() => {
try { readFileSync('nope.txt'); return ''; }
catch (err) { return err instanceof FileError ? err.code : ''; }
})(), 'ENOENT');
Output
Adapted: the usual version uses Node's fs. The commented block shows the real call. The habit being taught survives the swap intact: branch on err.code === 'ENOENT' rather than on the message text, because message wording is not a stable API and changes between Node versions. Note too that an empty file and a missing file are different outcomes, and code that conflates them has a bug.