All files mustacheUtils.js

0% Statements 0/14
0% Branches 0/4
0% Functions 0/10
0% Lines 0/12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                                                                     
// @flow
 
import Mustache from 'mustache'
import fs from 'fs'
 
// =============================================================================
// Mustache related utilities
// =============================================================================
 
// Mustache render using a template file
// filename: Path to the template file
// view: Mustache view to apply to the template
// returns: Rendered string output
export async function mustacheRenderUsingTemplateFile (
  filename: string,
  view: any) {
  return readFile(filename, 'utf8')
      .then(template => Mustache.render(template, view))
}
 
// Mustache render to an output file using a template file
// templateFilename: Path to the template file
// view: Mustache view to apply to the template
// outputFile: Path to the output file
export async function mustacheRenderToOutputFileUsingTemplateFile (
  templateFilename: string,
  view: any,
  outputFile: string) {
  return mustacheRenderUsingTemplateFile(templateFilename, view).then(output => {
    return writeFile(outputFile, output)
  })
}
 
// =============================================================================
// Async wrappers
// =============================================================================
 
async function readFile (
  filename: string,
  enc: string) {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, enc, (err, res) => {
      if (err) reject(err)
      else resolve(res)
    })
  })
}
 
async function writeFile (
  filename: string,
  data: any) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, data, (err, res) => {
      if (err) reject(err)
      else resolve(res)
    })
  })
}