Skip to content

Commit

Permalink
feat: support fs.exists async function
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Dec 22, 2024
1 parent 153e3ff commit 3a1f9d6
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/fs.ts
Original file line number Diff line number Diff line change
@@ -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<Stats | false> {
try {
return await stat(file);
} catch (err: any) {
if (err.code === 'ENOENT') {
return false;
}
throw err;
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './string.js';
export * from './optimize.js';
export * from './object.js';
export * from './timeout.js';
export * from './fs.js';
30 changes: 30 additions & 0 deletions test/fs.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
});

0 comments on commit 3a1f9d6

Please sign in to comment.