From 3a1f9d62a64fcb17514f64fae4a9c0dbd52040b5 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Mon, 23 Dec 2024 00:42:25 +0800 Subject: [PATCH] feat: support fs.exists async function --- src/fs.ts | 17 +++++++++++++++++ src/index.ts | 1 + test/fs.test.ts | 30 ++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 src/fs.ts create mode 100644 test/fs.test.ts diff --git a/src/fs.ts b/src/fs.ts new file mode 100644 index 0000000..d1e3a87 --- /dev/null +++ b/src/fs.ts @@ -0,0 +1,17 @@ +import { Stats } from 'node:fs'; +import { stat } from 'node:fs/promises'; + +/** + * Check if a file exists. + * Returns the file stats if it exists, or `false` if it doesn't. + */ +export async function exists(file: string): Promise { + try { + return await stat(file); + } catch (err: any) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } +} diff --git a/src/index.ts b/src/index.ts index aecde29..ee2c139 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,3 +9,4 @@ export * from './string.js'; export * from './optimize.js'; export * from './object.js'; export * from './timeout.js'; +export * from './fs.js'; diff --git a/test/fs.test.ts b/test/fs.test.ts new file mode 100644 index 0000000..957422b --- /dev/null +++ b/test/fs.test.ts @@ -0,0 +1,30 @@ +import { strict as assert } from 'node:assert'; +import path from 'node:path'; +import { Stats } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import * as utility from '../src/index.js'; +import { exists } from '../src/index.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +describe('test/fs.test.ts', () => { + describe('exists()', () => { + it('should work', async () => { + let stats = await exists(__filename); + assert(stats instanceof Stats); + assert(stats.size > 0, 'stats.size > 0'); + assert.equal(stats.isFile(), true); + assert.equal(stats.isDirectory(), false); + + stats = await utility.exists(__dirname); + assert(stats instanceof Stats); + assert(stats.size > 0, 'stats.size > 0'); + assert.equal(stats.isDirectory(), true); + assert.equal(stats.isFile(), false); + assert.equal(await exists(__dirname + '/nonexistent'), false); + + assert.equal(await exists('/root/../../../../../etc/passwd'), false); + }); + }); +});