Skip to content
This repository was archived by the owner on Sep 17, 2022. It is now read-only.

Commit 46c846a

Browse files
committed
file_system: remove reamining fs.exists calls
Instead, use fs.stat and fs.readFile directly and let them throw if the file in question does not exist, and format the error in a way how we want using a small helper function.
1 parent 8faf2b4 commit 46c846a

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/io/file_system.ts

+15-10
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import * as fs from 'fs';
2020
import {dirname, join, resolve} from 'path';
2121
import {promisify} from 'util';
2222

23-
const exists = promisify(fs.exists);
2423
const stat = promisify(fs.stat);
2524
const writeFile = promisify(fs.writeFile);
2625
const readFile = promisify(fs.readFile);
@@ -29,6 +28,17 @@ const mkdir = promisify(fs.mkdir);
2928
// tslint:disable-next-line:max-line-length
3029
import {getModelArtifactsInfoForJSON, toArrayBuffer, toBuffer} from './io_utils';
3130

31+
function notExist(name: string): (e: NodeJS.ErrnoException) => never {
32+
return e => {
33+
switch (e.code) {
34+
case 'ENOENT':
35+
throw new Error(`${name} ${e.path} does not exist: loading failed`);
36+
default:
37+
throw e;
38+
}
39+
};
40+
}
41+
3242
export class NodeFileSystem implements tfc.io.IOHandler {
3343
static readonly URL_SCHEME = 'file://';
3444

@@ -107,13 +117,11 @@ export class NodeFileSystem implements tfc.io.IOHandler {
107117
// https://github.com/tensorflow/tfjs/issues/343
108118
}
109119

110-
if (!await exists(this.path)) {
111-
throw new Error(`Path ${this.path} does not exist: loading failed.`);
112-
}
120+
const info = await stat(this.path).catch(notExist('Path'));
113121

114122
// `this.path` can be either a directory or a file. If it is a file, assume
115123
// it is model.json file.
116-
if ((await stat(this.path)).isFile()) {
124+
if (info.isFile()) {
117125
const modelJSON = JSON.parse(await readFile(this.path, 'utf8'));
118126

119127
const modelArtifacts: tfc.io.ModelArtifacts = {
@@ -126,11 +134,8 @@ export class NodeFileSystem implements tfc.io.IOHandler {
126134
for (const group of modelJSON.weightsManifest) {
127135
for (const path of group.paths) {
128136
const weightFilePath = join(dirName, path);
129-
if (!await exists(weightFilePath)) {
130-
throw new Error(`Weight file ${
131-
weightFilePath} does not exist: loading failed`);
132-
}
133-
const buffer = await readFile(weightFilePath);
137+
const buffer = await readFile(weightFilePath)
138+
.catch(notExist('Weight file'));
134139
buffers.push(buffer);
135140
}
136141
weightSpecs.push(...group.weights);

0 commit comments

Comments
 (0)