Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Created February 7, 2021 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/bf725b37467b10b56f29edd7e17e4190 to your computer and use it in GitHub Desktop.
Save Oaphi/bf725b37467b10b56f29edd7e17e4190 to your computer and use it in GitHub Desktop.
Recursive append Node.js utility
import { BaseEncodingOptions } from "fs";
import { appendFile, mkdir } from "fs/promises";
import { parse, sep } from "path";
const recursiveAppend = async (
path: string,
encoding: BaseEncodingOptions["encoding"] = "utf-8"
) => {
const parts = path.split(sep);
const lastPart = parts.pop();
if (!lastPart) return;
const onlyDirs = parse(lastPart).ext === "";
if (onlyDirs) parts.push(lastPart);
await mkdir(parts.join(sep), { recursive: true });
if (!onlyDirs) {
await appendFile(path, "", { encoding });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment