UNPKG

1.12 kBJavaScriptView Raw
1'use strict';
2
3var Bluebird = require('bluebird');
4var Fs = Bluebird.promisifyAll(require('fs'));
5
6var STDOUT_PATH = '-';
7
8/**
9 * Resolves if the file exists, rejects otherwise.
10 * @param {String} path - path of the file to check
11 * @returns {Promise}
12 */
13exports.exists = function (path) {
14 return Fs.statAsync(path);
15};
16
17/**
18 * Read a files contents if it exists, return the empty string otherwise.
19 * @param {String} path - path of the file to read
20 * @returns {Promise<String>} contents of the file
21 */
22exports.readIfExists = function (path) {
23 return Fs.readFileAsync(path, 'utf8')
24 .catch(function () {
25 return '';
26 });
27};
28
29/**
30 * Write the data to the specified file (or to stdout if file is '-').
31 * @param {String} path - path of the file to write to or '-' for stdout
32 * @param {String|Buffer} data - data to write
33 * @returns {Promise}
34 */
35exports.writeToFile = function (path, data) {
36 return Bluebird.resolve()
37 .then(function () {
38 if (path === STDOUT_PATH) {
39 return Fs.writeAsync(process.stdout.fd, data);
40 } else {
41 return Fs.writeFileAsync(path, data);
42 }
43 });
44};