index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const {promisify} = require('util');
  3. const path = require('path');
  4. const fs = require('graceful-fs');
  5. const isStream = require('is-stream');
  6. const makeDir = require('make-dir');
  7. const uuid = require('uuid');
  8. const tempDir = require('temp-dir');
  9. const writeFileP = promisify(fs.writeFile);
  10. const tempfile = filePath => path.join(tempDir, uuid.v4(), (filePath || ''));
  11. const writeStream = async (filePath, fileContent) => new Promise((resolve, reject) => {
  12. const writable = fs.createWriteStream(filePath);
  13. fileContent
  14. .on('error', error => {
  15. // Be careful to reject before writable.end(), otherwise the writable's
  16. // 'finish' event will fire first and we will resolve the promise
  17. // before we reject it.
  18. reject(error);
  19. fileContent.unpipe(writable);
  20. writable.end();
  21. })
  22. .pipe(writable)
  23. .on('error', reject)
  24. .on('finish', resolve);
  25. });
  26. module.exports = async (fileContent, filePath) => {
  27. const tempPath = tempfile(filePath);
  28. const write = isStream(fileContent) ? writeStream : writeFileP;
  29. await makeDir(path.dirname(tempPath));
  30. await write(tempPath, fileContent);
  31. return tempPath;
  32. };
  33. module.exports.sync = (fileContent, filePath) => {
  34. const tempPath = tempfile(filePath);
  35. makeDir.sync(path.dirname(tempPath));
  36. fs.writeFileSync(tempPath, fileContent);
  37. return tempPath;
  38. };