diff options
Diffstat (limited to 'std/fs/write_json.ts')
-rw-r--r-- | std/fs/write_json.ts | 51 |
1 files changed, 27 insertions, 24 deletions
diff --git a/std/fs/write_json.ts b/std/fs/write_json.ts index 015957bba..46c33572a 100644 --- a/std/fs/write_json.ts +++ b/std/fs/write_json.ts @@ -2,32 +2,43 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any type Replacer = (key: string, value: any) => any; -export interface WriteJsonOptions { - spaces?: number | string; +export interface WriteJsonOptions extends Deno.WriteFileOptions { replacer?: Array<number | string> | Replacer; + spaces?: number | string; } -/* Writes an object to a JSON file. */ -export async function writeJson( +function serialize( filePath: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any object: any, - options: WriteJsonOptions = {}, -): Promise<void> { - let contentRaw = ""; - + options: WriteJsonOptions, +): string { try { - contentRaw = JSON.stringify( + const jsonString = JSON.stringify( object, options.replacer as string[], options.spaces, ); + return `${jsonString}\n`; } catch (err) { err.message = `${filePath}: ${err.message}`; throw err; } +} - await Deno.writeFile(filePath, new TextEncoder().encode(contentRaw)); +/* 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, + }); } /* Writes an object to a JSON file. */ @@ -37,18 +48,10 @@ export function writeJsonSync( object: any, options: WriteJsonOptions = {}, ): void { - let contentRaw = ""; - - try { - contentRaw = JSON.stringify( - object, - options.replacer as string[], - options.spaces, - ); - } catch (err) { - err.message = `${filePath}: ${err.message}`; - throw err; - } - - Deno.writeFileSync(filePath, new TextEncoder().encode(contentRaw)); + const jsonString = serialize(filePath, object, options); + Deno.writeTextFileSync(filePath, jsonString, { + append: options.append, + create: options.create, + mode: options.mode, + }); } |