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');
10 const tempfile = filepath => path.join(tempDir, uuid.v4(), (filepath || ''));
12 const writeStream = (filepath, input) => new Promise((resolve, reject) => {
13 const writable = fs.createWriteStream(filepath);
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.
21 input.unpipe(writable);
26 .on('finish', resolve);
29 module.exports = (input, filepath) => {
30 const tempPath = tempfile(filepath);
31 const write = isStream(input) ? writeStream : pify(fs.writeFile);
33 return makeDir(path.dirname(tempPath))
34 .then(() => write(tempPath, input))
35 .then(() => tempPath);
38 module.exports.sync = (input, filepath) => {
39 const tempPath = tempfile(filepath);
41 makeDir.sync(path.dirname(tempPath));
42 fs.writeFileSync(tempPath, input);