.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / temp-write / index.js
1 'use strict';
2 const path = require('path');
3 const fs = require('graceful-fs');
4 const isStream = require('is-stream');
5 const makeDir = require('make-dir');
6 const uuid = require('uuid');
7 const pify = require('pify');
8 const tempDir = require('temp-dir');
9
10 const tempfile = filepath => path.join(tempDir, uuid.v4(), (filepath || ''));
11
12 const writeStream = (filepath, input) => new Promise((resolve, reject) => {
13         const writable = fs.createWriteStream(filepath);
14
15         input
16                 .on('error', err => {
17                         // Be careful to reject before writable.end(), otherwise the writable's
18                         // 'finish' event will fire first and we will resolve the promise
19                         // before we reject it.
20                         reject(err);
21                         input.unpipe(writable);
22                         writable.end();
23                 })
24                 .pipe(writable)
25                 .on('error', reject)
26                 .on('finish', resolve);
27 });
28
29 module.exports = (input, filepath) => {
30         const tempPath = tempfile(filepath);
31         const write = isStream(input) ? writeStream : pify(fs.writeFile);
32
33         return makeDir(path.dirname(tempPath))
34                 .then(() => write(tempPath, input))
35                 .then(() => tempPath);
36 };
37
38 module.exports.sync = (input, filepath) => {
39         const tempPath = tempfile(filepath);
40
41         makeDir.sync(path.dirname(tempPath));
42         fs.writeFileSync(tempPath, input);
43
44         return tempPath;
45 };