Skip to content

Commit

Permalink
feat(public/fs): adds read
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed May 11, 2019
1 parent db4dda5 commit 41b3118
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/public/fs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ export { default as json } from './json';
export { default as remove } from './remove';
export { default as mkdir } from './mkdir';
export { default as move } from './move';
export { default as read } from './read';
export { default as rw } from './rw';
export { default as write } from './write';
27 changes: 27 additions & 0 deletions src/public/fs/read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import fs from 'fs-extra';
import { exists, absolute } from '~/utils/file';
import expose from '~/utils/expose';
import { IFsReadOptions } from './types';
import { TScript } from '~/types';

export default expose(read);

/**
* Reads a `file` and passes it as an argument to a callback `fn`, which can return a `TScript`.
* It is an *exposed* function: call `read.fn()`, which takes the same arguments, in order to execute on call.
* @returns An asynchronous function -hence, calling `read` won't have any effect until the returned function is called.
*/
function read(
file: string,
fn: (raw?: string) => TScript,
options: IFsReadOptions = {}
): () => Promise<TScript> {
return async () => {
const cwd = process.cwd();
file = absolute({ path: file, cwd });
const doesExist = await exists(file, { fail: options.fail });
const raw = doesExist ? await fs.readFile(file).then(String) : undefined;

return fn(raw);
};
}
14 changes: 12 additions & 2 deletions src/public/fs/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
/**
* Options taken by read *fs* functions.
*/
export interface IFsReadOptions {
/**
* If `false`, it won't fail if a path doesn't exist for a read, or if it already exists for a write. Defaults to `false`.
*/
fail?: boolean;
}

/**
* Options taken by *fs* functions.
*/
export interface IFsOptions {
export interface IFsOptions extends IFsReadOptions {
/**
* If `true`, it will require user confirmation for removal. Defaults to `false`.
*/
Expand All @@ -13,7 +23,7 @@ export interface IFsOptions {
}

/**
* Options taken by *fs* read functions.
* Options taken by *fs* write functions.
*/
export interface IFsWriteOptions extends IFsOptions {
/**
Expand Down

0 comments on commit 41b3118

Please sign in to comment.