diff --git a/src/public/fs/index.ts b/src/public/fs/index.ts index 9ebbe20..d0b449f 100644 --- a/src/public/fs/index.ts +++ b/src/public/fs/index.ts @@ -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'; diff --git a/src/public/fs/read.ts b/src/public/fs/read.ts new file mode 100644 index 0000000..889f5a5 --- /dev/null +++ b/src/public/fs/read.ts @@ -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 { + 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); + }; +} diff --git a/src/public/fs/types.ts b/src/public/fs/types.ts index 54676d6..cc155c8 100644 --- a/src/public/fs/types.ts +++ b/src/public/fs/types.ts @@ -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`. */ @@ -13,7 +23,7 @@ export interface IFsOptions { } /** - * Options taken by *fs* read functions. + * Options taken by *fs* write functions. */ export interface IFsWriteOptions extends IFsOptions { /**