Skip to content

Commit

Permalink
feat(file): exists
Browse files Browse the repository at this point in the history
  • Loading branch information
seb-cr committed May 9, 2023
1 parent a3bdac0 commit f165d20
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 3 deletions.
1 change: 1 addition & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ extends:

rules:
'@typescript-eslint/no-non-null-assertion': off
'@typescript-eslint/no-explicit-any': off
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,20 @@ const output = await exec('echo hello');

### File manipulation

Check whether a file exists using `exists`.

```ts
if (await exists('somefile')) {
// do something
}
```

Most other file operations (delete, copy, rename) are already easy enough using Node's `fs/promises` API. Documentation for these can be found [here](https://nodejs.org/api/fs.html#promises-api).

```ts
import { rm, copyFile, rename } from 'fs/promises';
```

Work with text files using the `withFile` function. It opens the file, passes the content to a callback for editing, then saves it back if any changes were made.

```ts
Expand Down
23 changes: 22 additions & 1 deletion src/file.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
import { readFile, writeFile } from 'fs/promises';
import {
access,
readFile,
writeFile,
} from 'fs/promises';
import { EOL } from 'os';

import { Text } from './text';

/**
* Check whether the given file or directory exists.
*
* @param path File or directory path.
*/
export async function exists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch (error: any) {
if (error.code === 'ENOENT') {
return false;
}
throw error;
}
}

/**
* Work with a text file.
*
Expand Down
18 changes: 16 additions & 2 deletions tests/file.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,25 @@ import { readFile, unlink, writeFile } from 'fs/promises';

import { expect } from 'chai';

import { withFile } from '@/src';
import { exists, withFile } from '@/src';

const TEST_FILE = 'test.tmp';
describe('exists', () => {
it('should return true if the path is a file', async () => {
expect(await exists('README.md')).to.be.true;
});

it('should return true if the path is a directory', async () => {
expect(await exists('tests')).to.be.true;
});

it('should return false if the path does not exist', async () => {
expect(await exists('nonexistent')).to.be.false;
});
});

describe('withFile', () => {
const TEST_FILE = 'test.tmp';

before('create test file', async () => {
await writeFile(TEST_FILE, 'hello world');
});
Expand Down

0 comments on commit f165d20

Please sign in to comment.