@augment-vir/node
Version:
A collection of augments, helpers types, functions, and classes only for Node.js (backend) JavaScript environments.
57 lines (56 loc) • 1.87 kB
JavaScript
import { appendJson, } from '@augment-vir/common';
import { mkdir, readFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { writeFileAndDir } from './write.js';
/**
* Read a file and also parse its contents as JSON.
*
* @category Node : File
* @category JSON : Node
* @category Package : @augment-vir/node
* @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
* @see
* - {@link writeJsonFile}
* - {@link appendJsonFile}
*/
export async function readJsonFile(path) {
try {
const contents = (await readFile(path)).toString();
return JSON.parse(contents);
}
catch {
return undefined;
}
}
/**
* Write to a file and stringify `data` as JSON before doing so.
*
* @category Node : File
* @category JSON : Node
* @category Package : @augment-vir/node
* @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
* @see
* - {@link readJsonFile}
* - {@link appendJsonFile}
*/
export async function writeJsonFile(path, data, options = {}) {
await mkdir(dirname(path), { recursive: true });
const trailingNewLine = options.includeTrailingNewLine ? '\n' : '';
await writeFileAndDir(path, JSON.stringify(data, null, 4) + trailingNewLine);
}
/**
* Append the given `newData` to the contents of the existing JSON file. If the file does not yet
* exist, `newData` is written as its only JSON contents.
*
* @category Node : File
* @category JSON : Node
* @category Package : @augment-vir/node
* @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
* @see
* - {@link readJsonFile}
* - {@link writeJsonFile}
*/
export async function appendJsonFile(path, newData, options = {}) {
const fileJson = await readJsonFile(path);
await writeJsonFile(path, appendJson(fileJson, newData), options);
}