diff options
author | Marcin Puc <5671049+tranzystorek-io@users.noreply.github.com> | 2020-07-26 21:51:33 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-07-26 15:51:33 -0400 |
commit | 7326e1ab490aab2220b139460165be0bfbf04f36 (patch) | |
tree | 1aff54e9bb747e46fa62c834d3bc85f965f868cb /std/fs/write_json.ts | |
parent | 3b7fdd6734c4f1dbc34b0971296464395dc173bf (diff) |
fix(std/json): Add newline at the end of json files (#6885)
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, + }); } |