File/tryWriteFile.js

/**
 * Attempts to write given data to a file.
 *
 * @function tryWriteFile
 * @since 1.0.0
 * @memberof module:File
 *
 * @param {string} filepath - Path to an existing or new file you want to write to
 * @param {string} data - The data you would like to write to the file
 * @param {string|object} [options='utf8'] - The options object or a string with the encoding
 *
 * @return {promise} A promise that resolves if successfully written to file
 * @example
 * import { tryWriteFile } from 'fenix-tools'
 *
 * tryWriteFile('path/to/file', 'Data to write to file', 'utf8')
 * .then(() => {
 *  // Success writing file to machine
 * })
 *
 */
export default function tryWriteFile (filepath, data, options = 'utf8') {
  const fs = require('fs')
  return new Promise((resolve, reject) => {
    try {
      fs.writeFile(filepath, data, options, (error) => {
        if (error !== 'undefined' && error !== null) {
          resolve()
        }
      })
    } catch (error) { reject(error) }
  })
}