Skip to content

Commit

Permalink
feat(node-fs): readFile under asyncQueue
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jan 8, 2024
1 parent 8faf1c4 commit d379926
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
22 changes: 13 additions & 9 deletions packages/node-fs/src/read-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {readFile as readFile_} from 'node:fs/promises';

import {flatString} from '@alwatr/flat-string';

import {logger} from './common';
import {asyncQueue, logger} from './common';

/**
* Enhanced read File (Synchronous).
Expand All @@ -30,21 +30,25 @@ export function readFileSync(path: string): string {
/**
* Enhanced read File (Asynchronous).
*
* - If writing queue is running for target path, it will wait for it to finish.
*
* @param path - file path
* @returns file content
* @example
* ```typescript
* const fileContent = await readFile('./file.txt', sync);
* ```
*/
export async function readFile(path: string): Promise<string> {
export function readFile(path: string): Promise<string> {
logger.logMethodArgs?.('readFile', '...' + path.slice(-32));
// if (!existsSync(path)) throw new Error('file_not_found');
try {
return flatString(await readFile_(path, {encoding: 'utf-8', flag: 'r'}));
}
catch (err) {
logger.error('readFile', 'read_file_failed', {path}, err);
throw new Error('read_file_failed', {cause: (err as Error).cause});
}
return asyncQueue.push(path, async () => {
try {
return flatString(await readFile_(path, {encoding: 'utf-8', flag: 'r'}));
}
catch (err) {
logger.error('readFile', 'read_file_failed', {path}, err);
throw new Error('read_file_failed', {cause: (err as Error).cause});
}
});
}
2 changes: 1 addition & 1 deletion packages/node-fs/src/write-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function writeFileSync(path: string, content: string): void {
* @param content - file content
* @example
* ```typescript
* writeFile('./file.txt', 'Hello World!');
* await writeFile('./file.txt', 'Hello World!');
* ```
*/
export function writeFile(path: string, content: string): Promise<void> {
Expand Down

0 comments on commit d379926

Please sign in to comment.