File/loadLocalFile.js

/**
 * Load a file on the local machine.
 *
 * @function loadLocalFile
 * @since 1.0.0
 * @memberof module:File
 *
 * @param {string} path - Path to the file.
 * @param {string} [encoding='utf8'] - The type of file encoding
 *
 * @return {promise} A promise that resolves the data
 * @example
 * import {loadLocalFile} from 'fenix-tools'
 *
 * loadLocalFile('./img/pictures/character1.png)
 * .then(data => {
 *  // Local file loaded success
 *  console.log(data)  // => A parsed JSON object.
 * })
 *
 */
export default function loadLocalFile (path, encoding = 'utf8') {
  const fs = require('fs')
  return new Promise((resolve, reject) => {
    if (fs.existsSync(path)) {
      const contents = fs.readFileSync(path, encoding, err => reject(err))
      resolve(contents)
    }
    reject(new Error(`Cannot read file at ${path}`))
  })
}