From e95db50555a9f02e241bea9753506e12a14b0395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Enes=20Gen=C3=A7?= Date: Sun, 12 Sep 2021 15:50:20 +0300 Subject: [PATCH] feat: add function to create files using templates --- src/functions/CreateFileFromTemplate.ts | 19 +++++++++++++++++++ src/functions/index.ts | 1 + 2 files changed, 20 insertions(+) create mode 100644 src/functions/CreateFileFromTemplate.ts diff --git a/src/functions/CreateFileFromTemplate.ts b/src/functions/CreateFileFromTemplate.ts new file mode 100644 index 0000000..85b912b --- /dev/null +++ b/src/functions/CreateFileFromTemplate.ts @@ -0,0 +1,19 @@ +import { readFile, writeFile } from 'fs/promises'; + +export function CreateFileFromTemplate(template: string, target: string, params?: Record, custom = false) { + return new Promise(async (resolve, reject) => { + const location = custom ? '' : `${__dirname}/../templates/`; + + let output = await readFile(`${location}${template}`, 'utf8'); + if (!output) return reject(new Error("Can't read file.")); + if (params) { + for (const param of Object.entries(params)) { + output = output.replaceAll(`{{${param[0]}}}`, param[1]); + } + } + + await writeFile(target, output).catch(reject); + + return resolve(true); + }); +} diff --git a/src/functions/index.ts b/src/functions/index.ts index 7e8b6d3..4a5c308 100644 --- a/src/functions/index.ts +++ b/src/functions/index.ts @@ -1 +1,2 @@ export * from './CommandExists'; +export * from './CreateFileFromTemplate';