From a5e1c15c1beb27b50728d374e95fe01c391647fd Mon Sep 17 00:00:00 2001 From: Aleksandr Statciuk Date: Thu, 11 May 2023 04:12:25 +0300 Subject: [PATCH] Update file.js --- src/file.js | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/file.js b/src/file.js index 339c438..5f02731 100644 --- a/src/file.js +++ b/src/file.js @@ -6,28 +6,47 @@ module.exports.write = write module.exports.resolve = resolve module.exports.join = join module.exports.dirname = dirname +module.exports.templateVariables = templateVariables +module.exports.templateFormat = templateFormat function read(filepath) { - return fs.readFileSync(path.resolve(filepath), { encoding: 'utf-8' }) + return fs.readFileSync(path.resolve(filepath), { encoding: 'utf-8' }) } function write(filepath, data) { - const dir = path.resolve(path.dirname(filepath)) - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }) - } + const dir = path.resolve(path.dirname(filepath)) + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }) + } - fs.writeFileSync(path.resolve(filepath), data) + fs.writeFileSync(path.resolve(filepath), data) } function resolve(filepath) { - return path.resolve(filepath) + return path.resolve(filepath) } function join(path1, path2) { - return path.join(path1, path2) + return path.join(path1, path2) } function dirname(filepath) { - return path.dirname(filepath) + return path.dirname(filepath) +} + +function templateVariables(template) { + const match = template.match(/{[^}]+}/g) + + return Array.isArray(match) ? match.map(s => s.substring(1, s.length - 1)) : [] +} + +function templateFormat(template, obj) { + let output = template + for (let key in obj) { + const regex = new RegExp(`{${key}}`, 'g') + const value = obj[key] || undefined + output = output.replace(regex, value) + } + + return output }