all files / lib/ file.js

100% Statements 13/13
100% Branches 2/2
100% Functions 5/5
100% Lines 13/13
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                                                               
'use strict';
 
var Bluebird = require('bluebird');
var Fs       = Bluebird.promisifyAll(require('fs'));
 
var STDOUT_PATH = '-';
 
/**
 * Resolves if the file exists, rejects otherwise.
 * @param {String} path - path of the file to check
 * @returns {Promise}
 */
exports.exists = function (path) {
  return Fs.statAsync(path);
};
 
/**
 * Read a files contents if it exists, return the empty string otherwise.
 * @param {String} path - path of the file to read
 * @returns {Promise<String>} contents of the file
 */
exports.readIfExists = function (path) {
  return Fs.readFileAsync(path, 'utf8')
  .catch(function () {
    return '';
  });
};
 
/**
 * Write the data to the specified file (or to stdout if file is '-').
 * @param {String} path - path of the file to write to or '-' for stdout
 * @param {String|Buffer} data - data to write
 * @returns {Promise}
 */
exports.writeToFile = function (path, data) {
  return Bluebird.resolve()
  .then(function () {
    if (path === STDOUT_PATH) {
      return Fs.writeAsync(process.stdout.fd, data);
    } else {
      return Fs.writeFileAsync(path, data);
    }
  });
};