From 72311e94e9825bc323003c35681217ad0abe200d Mon Sep 17 00:00:00 2001 From: Kevin Van Lierde Date: Wed, 1 Jun 2022 02:24:20 +0200 Subject: [PATCH] Adds support for methods: compileFileAsync, render, renderFile, renderFileAsync --- index.js | 57 +++++++++++++++++++++++++++++++++++++++++++------- test/input.ejs | 2 +- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index c9af649..43ca6b0 100644 --- a/index.js +++ b/index.js @@ -3,17 +3,58 @@ const fs = require('fs') const ejs = require('ejs') -exports.name = 'ejs' -exports.outputFormat = 'html' -exports.compile = ejs.compile -exports.compileClient = function (source, options) { +const transformer = { + name: 'ejs', + outputFormat: 'html', +} + +transformer.compile = function (source, options) { + return ejs.compile(source, { ...options, async: false, client: false }) +} + +transformer.compileClient = function (source, options) { + return ejs.compile(source, { ...options, async: false, client: true }).toString() +} + +transformer.compileFile = function (path, options) { options = options || {} - options.client = true - return exports.compile(source, options).toString() + options.filename = options.filename || path + return transformer.compile(fs.readFileSync(path, 'utf8'), options) } -exports.compileFile = function (path, options) { +transformer.compileFileAsync = function (path, options) { options = options || {} options.filename = options.filename || path - return exports.compile(fs.readFileSync(path, 'utf8'), options) + return new Promise((resolve, reject) => { + fs.readFile(path, 'utf8', (error, source) => { + if (error) { + reject(error) + } + + resolve(transformer.compile(source, options)) + }) + }) } + +transformer.render = function (source, options, locals) { + return ejs.render(source, locals, { ...options, async: false }) +} + +transformer.renderFile = function (path, options, locals = null) { + options.filename = options.filename || path + return ejs.render(fs.readFileSync(path, 'utf8'), locals, { ...options, async: false }) +} + +transformer.renderFileAsync = function (path, options, locals = null) { + return new Promise((resolve, reject) => { + ejs.renderFile(path, locals, options, (error, result) => { + if (error) { + reject(error) + } + + resolve(result) + }) + }) +} + +module.exports = transformer diff --git a/test/input.ejs b/test/input.ejs index f2728c5..e736f80 100644 --- a/test/input.ejs +++ b/test/input.ejs @@ -1,5 +1,5 @@