@@ -5,6 +5,7 @@ module.exports.pathBasename = pathBasename
55module . exports . getFullUri = getFullUri
66module . exports . hasSuffix = hasSuffix
77module . exports . parse = parse
8+ module . exports . processHandlebarFile = processHandlebarFile
89module . exports . serialize = serialize
910module . exports . translate = translate
1011module . exports . stringToStream = stringToStream
@@ -19,6 +20,8 @@ const path = require('path')
1920const $rdf = require ( 'rdflib' )
2021const from = require ( 'from2' )
2122const url = require ( 'url' )
23+ const Handlebars = require ( 'handlebars' )
24+ const debug = require ( './debug' ) . errors
2225
2326/**
2427 * Returns a fully qualified URL from an Express.js Request object.
@@ -147,6 +150,54 @@ function parse (data, baseUri, contentType, callback) {
147150 }
148151}
149152
153+ /**
154+ * Reads a file, processes it (performing template substitution), and saves
155+ * back the processed result.
156+ *
157+ * @param filePath {string}
158+ * @param substitutions {Object}
159+ *
160+ * @return {Promise }
161+ */
162+ async function processHandlebarFile ( filePath , substitutions ) {
163+ return new Promise ( ( resolve , reject ) => {
164+ fs . readFile ( filePath , 'utf8' , ( error , rawSource ) => {
165+ if ( error ) {
166+ return reject ( error )
167+ }
168+
169+ const output = processHandlebarTemplate ( rawSource , substitutions )
170+
171+ fs . writeFile ( filePath , output , ( error ) => {
172+ if ( error ) {
173+ return reject ( error )
174+ }
175+ resolve ( )
176+ } )
177+ } )
178+ } )
179+ }
180+
181+ /**
182+ * Performs a Handlebars string template substitution, and returns the
183+ * resulting string.
184+ *
185+ * @see https://www.npmjs.com/package/handlebars
186+ *
187+ * @param source {string} e.g. 'Hello, {{name}}'
188+ *
189+ * @return {string } Result, e.g. 'Hello, Alice'
190+ */
191+ function processHandlebarTemplate ( source , substitutions ) {
192+ try {
193+ const template = Handlebars . compile ( source )
194+ return template ( substitutions )
195+ } catch ( error ) {
196+ debug ( `Error processing template: ${ error } ` )
197+ return source
198+ }
199+ }
200+
150201function serialize ( graph , baseUri , contentType , callback ) {
151202 try {
152203 // target, kb, base, contentType, callback
0 commit comments