-
Notifications
You must be signed in to change notification settings - Fork 161
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: support fs.exists async function
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); | ||
}); |