Skip to content

Commit

Permalink
feat(node-fs): writeJson method
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jan 8, 2024
1 parent 6dc32d8 commit 58fd97c
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions packages/node-fs/src/write-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {flatString} from '@alwatr/flat-string';

import {jsonStringify} from './json';
import {logger} from './logger';
import {writeFile, writeFileSync} from './write-file.js';

import type {MaybePromise} from '@alwatr/type-helper';

/**
* Enhanced write json file (Asynchronous).
*
* @param path - file path
* @param data - json object
* @example
* ```typescript
* await writeJsonFile('./file.json', { a:1, b:2, c:3 });
* ```
*/
export function writeJson(path: string, data: unknown, sync?: false): Promise<void>;
/**
* Enhanced write json file (Synchronous).
*
* @param path - file path
* @param data - json object
* @param sync - sync mode
* @example
* ```typescript
* writeJsonFile('./file.json', { a:1, b:2, c:3 }, true);
* ```
*/
export function writeJson(path: string, data: unknown, sync: true): void;
/**
* Enhanced write json file.
*
* @param path - file path
* @param data - json object
* @param sync - sync mode
* @example
* ```typescript
* await writeJsonFile('./file.json', { a:1, b:2, c:3 }, sync);
* ```
*/
export function writeJson(path: string, data: unknown, sync: boolean): MaybePromise<void>;
/**
* Enhanced write json file.
*
* @param path - file path
* @param data - json object
* @param sync - sync mode
* @example
* ```typescript
* await writeJsonFile('./file.json', { a:1, b:2, c:3 });
* ```
*/
export function writeJson(path: string, data: unknown, sync = false): MaybePromise<void> {
logger.logMethodArgs?.('writeJson', '...' + path.slice(-32));
const content = flatString(jsonStringify(data));
return sync === true ? writeFileSync(path, content) : writeFile(path, content);
}

0 comments on commit 58fd97c

Please sign in to comment.