Skip to content

Commit 723a770

Browse files
committed
feat(node-fs): enhance makeEmptyFile to create directories recursively if they don't exist
1 parent 7d12943 commit 723a770

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

packages/node-fs/src/make-file.ts

+18-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import {open} from 'node:fs/promises';
1+
import { existsSync } from 'node:fs';
2+
import {mkdir, open} from 'node:fs/promises';
3+
import { dirname } from 'node:path';
24

35
import {logger} from './common.js';
46

@@ -9,10 +11,23 @@ import {logger} from './common.js';
911
*
1012
* @example
1113
* ```ts
12-
* await makeFile('./file.txt');
14+
* await makeFile('./dir/file.txt');
1315
* ```
1416
*/
1517
export async function makeEmptyFile(path: string): Promise<void> {
1618
logger.logMethodArgs?.('makeEmptyFile', '...' + path.slice(-32));
17-
return (await open(path, 'w')).close();
19+
try {
20+
const pathExists = existsSync(path);
21+
if (!pathExists) {
22+
const dir = dirname(path);
23+
if (!existsSync(dir)) {
24+
await mkdir(dir, {recursive: true});
25+
}
26+
}
27+
await (await open(path, 'w')).close();
28+
}
29+
catch (err) {
30+
logger.error('makeEmptyFile', 'make_file_failed', {path}, err);
31+
throw new Error('make_file_failed', {cause: (err as Error).cause});
32+
}
1833
}

0 commit comments

Comments
 (0)