diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..6b4f027 --- /dev/null +++ b/index.d.ts @@ -0,0 +1,44 @@ +export type Reviver = (key: string, value: any) => any; +export type BeforeParse = (data: string) => string; + +export interface Options { + /** + * Applies a function to the JSON string before parsing. + */ + beforeParse?: BeforeParse; + /** + * Prescribes how the value originally produced by parsing is transformed, before being returned. + * See the [`JSON.parse` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) for more. + */ + reviver?: Reviver; +} + +/** + * Read and parse a JSON file. + * + * Strips UTF-8 BOM, uses graceful-fs, and throws more helpful JSON errors. + * + * @example + * + * import * as loadJsonFile from 'load-json-file'; + * + * const json = loadJsonFile.sync('foo.json'); + * //=> {foo: true} + */ +export function sync(filePath: string, options?: Options): T; + +/** + * Read and parse a JSON file. + * + * Strips UTF-8 BOM, uses graceful-fs, and throws more helpful JSON errors. + * + * @example + * + * import loadJsonFile from 'load-json-file'; + * + * (async () => { + * const json = await loadJsonFile('foo.json'); + * //=> {foo: true} + * })(); + */ +export default function loadJsonFile(filePath: string, options?: Options): Promise; diff --git a/index.js b/index.js index 7828e2a..0b9a86b 100644 --- a/index.js +++ b/index.js @@ -15,5 +15,8 @@ const parse = (data, filePath, options = {}) => { return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); }; -module.exports = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); +const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); + +module.exports = loadJsonFile; +module.exports.default = loadJsonFile; module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); diff --git a/index.test-d.ts b/index.test-d.ts new file mode 100644 index 0000000..aae4191 --- /dev/null +++ b/index.test-d.ts @@ -0,0 +1,12 @@ +import {expectType} from 'tsd-check'; +import loadJsonFile, {sync, Reviver, BeforeParse} from '.'; + +expectType(() => 1); +expectType((a: string) => a.length); +expectType((a: string, b: string) => a.length - b.length); + +expectType((data) => data); + +expectType(await loadJsonFile('unicorn.json')); + +expectType(sync('unicorn.json')); diff --git a/package.json b/package.json index 292f1b3..ecdd442 100644 --- a/package.json +++ b/package.json @@ -13,10 +13,11 @@ "node": ">=6" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd-check" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "keywords": [ "read", @@ -35,6 +36,7 @@ }, "devDependencies": { "ava": "*", + "tsd-check": "^0.2.1", "xo": "*" } }