2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-06-12 09:19:29 -04:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2019-03-14 10:26:12 -04:00
|
|
|
type Replacer = (key: string, value: any) => any;
|
|
|
|
|
2020-07-26 15:51:33 -04:00
|
|
|
export interface WriteJsonOptions extends Deno.WriteFileOptions {
|
2019-03-14 10:26:12 -04:00
|
|
|
replacer?: Array<number | string> | Replacer;
|
2020-07-26 15:51:33 -04:00
|
|
|
spaces?: number | string;
|
2019-03-14 10:26:12 -04:00
|
|
|
}
|
|
|
|
|
2020-07-26 15:51:33 -04:00
|
|
|
function serialize(
|
2019-03-14 10:26:12 -04:00
|
|
|
filePath: string,
|
2020-06-12 09:19:29 -04:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2019-03-14 10:26:12 -04:00
|
|
|
object: any,
|
2020-07-26 15:51:33 -04:00
|
|
|
options: WriteJsonOptions,
|
|
|
|
): string {
|
2019-03-14 10:26:12 -04:00
|
|
|
try {
|
2020-07-26 15:51:33 -04:00
|
|
|
const jsonString = JSON.stringify(
|
2019-03-14 10:26:12 -04:00
|
|
|
object,
|
|
|
|
options.replacer as string[],
|
2020-07-14 15:24:17 -04:00
|
|
|
options.spaces,
|
2019-03-14 10:26:12 -04:00
|
|
|
);
|
2020-07-26 15:51:33 -04:00
|
|
|
return `${jsonString}\n`;
|
2019-03-14 10:26:12 -04:00
|
|
|
} catch (err) {
|
|
|
|
err.message = `${filePath}: ${err.message}`;
|
|
|
|
throw err;
|
|
|
|
}
|
2020-07-26 15:51:33 -04:00
|
|
|
}
|
2019-03-14 10:26:12 -04:00
|
|
|
|
2020-07-26 15:51:33 -04:00
|
|
|
/* Writes an object to a JSON file. */
|
|
|
|
export async function writeJson(
|
|
|
|
filePath: string,
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
object: any,
|
|
|
|
options: WriteJsonOptions = {},
|
|
|
|
): Promise<void> {
|
|
|
|
const jsonString = serialize(filePath, object, options);
|
|
|
|
await Deno.writeTextFile(filePath, jsonString, {
|
|
|
|
append: options.append,
|
|
|
|
create: options.create,
|
|
|
|
mode: options.mode,
|
|
|
|
});
|
2019-03-14 10:26:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/* Writes an object to a JSON file. */
|
|
|
|
export function writeJsonSync(
|
|
|
|
filePath: string,
|
2020-06-12 09:19:29 -04:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2019-03-14 10:26:12 -04:00
|
|
|
object: any,
|
2020-07-14 15:24:17 -04:00
|
|
|
options: WriteJsonOptions = {},
|
2019-03-14 10:26:12 -04:00
|
|
|
): void {
|
2020-07-26 15:51:33 -04:00
|
|
|
const jsonString = serialize(filePath, object, options);
|
|
|
|
Deno.writeTextFileSync(filePath, jsonString, {
|
|
|
|
append: options.append,
|
|
|
|
create: options.create,
|
|
|
|
mode: options.mode,
|
|
|
|
});
|
2019-03-14 10:26:12 -04:00
|
|
|
}
|