Skip to content

Commit

Permalink
#1 add delete method to File class to make it easy to delete files
Browse files Browse the repository at this point in the history
  • Loading branch information
gdman committed Apr 25, 2021
1 parent 2c23820 commit b3524cf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/core/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ export class File {
}
};

public delete = async (): Promise<void> => {
try {
const file = this.getFile();

if (!fs.existsSync(file)) {
throw new Error('File not found');
}

await fs.promises.unlink(file);

return Promise.resolve();
} catch (ex) {
return Promise.reject('Delete failed: ' + (ex.message || ex));
}
}

private getParser = (): ParserInterface => {
if (this.parser) {
return this.parser;
Expand Down
13 changes: 13 additions & 0 deletions test/core/file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { File } from "../../src/core";
import { JsonParser, StringParser } from "../../src/parsers";
import { DataType, Metadata } from "../../src/types";
import { createTestFile, getTestFilePath, readTestFile } from "../test-utils/file-utils";
import * as fs from 'fs';

class NullBuilder implements BuilderInterface {
build(data: Metadata): Promise<string> {
Expand Down Expand Up @@ -251,4 +252,16 @@ describe('File', () => {
readTestFile(testFile)
).toBe('');
});

it('delete file that exists is successful', async () => {
const testFile = createTestFile('txt', 'value');

await new File(testFile).delete();

expect(fs.existsSync(testFile)).toBe(false);
});

it('delete file that doesnt exist rejects', () => {
return expect(new File('doesnt-exist').delete()).rejects.toBe('Delete failed: File not found');
});
});

0 comments on commit b3524cf

Please sign in to comment.