summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/node_modules/write/index.js
blob: f952638d0d4520177c2859ba64893109553e1699 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*!
 * write <https://github.com/jonschlinkert/write>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var mkdir = require('mkdirp');

/**
 * Asynchronously write a file to disk. Creates any intermediate
 * directories if they don't already exist.
 *
 * ```js
 * var writeFile = require('write');
 * writeFile('foo.txt', 'This is content to write.', function(err) {
 *   if (err) console.log(err);
 * });
 * ```
 *
 * @name  writeFile
 * @param  {String} `dest` Destination file path
 * @param  {String} `str` String to write to disk.
 * @param  {Function} `callback`
 * @api public
 */

module.exports = function writeFile(dest, str, cb) {
  var dir = path.dirname(dest);
  fs.exists(dir, function (exists) {
    if (exists) {
      fs.writeFile(dest, str, cb);
    } else {
      mkdir(dir, function (err) {
        if (err) {
          return cb(err);
        } else {
          fs.writeFile(dest, str, cb);
        }
      });
    }
  });
};

/**
 * Synchronously write files to disk. Creates any intermediate
 * directories if they don't already exist.
 *
 * ```js
 * var writeFile = require('write');
 * writeFile.sync('foo.txt', 'This is content to write.');
 * ```
 *
 * @name  writeFile.sync
 * @param  {String} `dest` Destination file path
 * @param  {String} `str` String to write to disk.
 * @api public
 */

module.exports.sync = function writeFileSync(dest, str) {
  var dir = path.dirname(dest);
  if (!fs.existsSync(dir)) {
    mkdir.sync(dir);
  }
  fs.writeFileSync(dest, str);
};

/**
 * Uses `fs.createWriteStream`, but also creates any intermediate
 * directories if they don't already exist.
 *
 * ```js
 * var write = require('write');
 * write.stream('foo.txt');
 * ```
 *
 * @name  writeFile.stream
 * @param  {String} `dest` Destination file path
 * @return  {Stream} Returns a write stream.
 * @api public
 */

module.exports.stream = function writeFileStream(dest) {
  var dir = path.dirname(dest);
  if (!fs.existsSync(dir)) {
    mkdir.sync(dir);
  }
  return fs.createWriteStream(dest);
};