index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const uniqueString = require('unique-string');
  5. const tempDir = require('temp-dir');
  6. const isStream = require('is-stream');
  7. const stream = require('stream');
  8. const {promisify} = require('util');
  9. const pipeline = promisify(stream.pipeline);
  10. const {writeFile} = fs.promises;
  11. const getPath = (prefix = '') => path.join(tempDir, prefix + uniqueString());
  12. const writeStream = async (filePath, data) => pipeline(data, fs.createWriteStream(filePath));
  13. module.exports.file = options => {
  14. options = {
  15. ...options
  16. };
  17. if (options.name) {
  18. if (options.extension !== undefined && options.extension !== null) {
  19. throw new Error('The `name` and `extension` options are mutually exclusive');
  20. }
  21. return path.join(module.exports.directory(), options.name);
  22. }
  23. return getPath() + (options.extension === undefined || options.extension === null ? '' : '.' + options.extension.replace(/^\./, ''));
  24. };
  25. module.exports.directory = ({prefix = ''} = {}) => {
  26. const directory = getPath(prefix);
  27. fs.mkdirSync(directory);
  28. return directory;
  29. };
  30. module.exports.write = async (data, options) => {
  31. const filename = module.exports.file(options);
  32. const write = isStream(data) ? writeStream : writeFile;
  33. await write(filename, data);
  34. return filename;
  35. };
  36. module.exports.writeSync = (data, options) => {
  37. const filename = module.exports.file(options);
  38. fs.writeFileSync(filename, data);
  39. return filename;
  40. };
  41. Object.defineProperty(module.exports, 'root', {
  42. get() {
  43. return tempDir;
  44. }
  45. });