Skip to content

Commit

Permalink
refactor: use fs.promises in module loader
Browse files Browse the repository at this point in the history
  • Loading branch information
dnalborczyk committed Jan 29, 2022
1 parent 5364114 commit 5650387
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 26 deletions.
5 changes: 4 additions & 1 deletion browser/fs.ts
@@ -1,4 +1,7 @@
import { throwNoFileSystem } from './error';

export const readFile = throwNoFileSystem('fs.readFile');
export const promises = {
readFile: throwNoFileSystem('fs.readFile')
};

export const writeFile = throwNoFileSystem('fs.writeFile');
5 changes: 3 additions & 2 deletions src/ModuleLoader.ts
Expand Up @@ -29,7 +29,7 @@ import {
errUnresolvedImport,
errUnresolvedImportTreatedAsExternal
} from './utils/error';
import { readFile } from './utils/fs';
import { promises as fs } from './utils/fs';
import { isAbsolute, isRelative, resolve } from './utils/path';
import { Queue } from './utils/queue';
import relativeId from './utils/relativeId';
Expand Down Expand Up @@ -240,7 +240,8 @@ export class ModuleLoader {
let source: LoadResult;
try {
source = await this.readQueue.run(
async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await readFile(id))
async () =>
(await this.pluginDriver.hookFirst('load', [id])) ?? (await fs.readFile(id, 'utf8'))
);
} catch (err: any) {
timeEnd('load modules', 3);
Expand Down
27 changes: 4 additions & 23 deletions src/utils/fs.ts
@@ -1,28 +1,9 @@
import fs from 'fs';
import { promises as fs } from 'fs';
import { dirname } from './path';

export * from 'fs';

export const readFile = (file: string): Promise<string> =>
new Promise<string>((fulfil, reject) =>
fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents)))
);

function mkdirpath(path: string) {
const dir = dirname(path);
fs.mkdirSync(dir, { recursive: true });
}

export function writeFile(dest: string, data: string | Uint8Array): Promise<void> {
return new Promise<void>((fulfil, reject) => {
mkdirpath(dest);

fs.writeFile(dest, data, err => {
if (err) {
reject(err);
} else {
fulfil();
}
});
});
export async function writeFile(dest: string, data: string | Uint8Array): Promise<void> {
await fs.mkdir(dirname(dest), { recursive: true });
await fs.writeFile(dest, data);
}

0 comments on commit 5650387

Please sign in to comment.