index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const path = require('path');
  3. const trimRepeated = require('trim-repeated');
  4. const filenameReservedRegex = require('filename-reserved-regex');
  5. const stripOuter = require('strip-outer');
  6. // Doesn't make sense to have longer filenames
  7. const MAX_FILENAME_LENGTH = 100;
  8. const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g; // eslint-disable-line no-control-regex
  9. const reRelativePath = /^\.+/;
  10. const filenamify = (string, options = {}) => {
  11. if (typeof string !== 'string') {
  12. throw new TypeError('Expected a string');
  13. }
  14. const replacement = options.replacement === undefined ? '!' : options.replacement;
  15. if (filenameReservedRegex().test(replacement) && reControlChars.test(replacement)) {
  16. throw new Error('Replacement string cannot contain reserved filename characters');
  17. }
  18. string = string.replace(filenameReservedRegex(), replacement);
  19. string = string.replace(reControlChars, replacement);
  20. string = string.replace(reRelativePath, replacement);
  21. if (replacement.length > 0) {
  22. string = trimRepeated(string, replacement);
  23. string = string.length > 1 ? stripOuter(string, replacement) : string;
  24. }
  25. string = filenameReservedRegex.windowsNames().test(string) ? string + replacement : string;
  26. string = string.slice(0, MAX_FILENAME_LENGTH);
  27. return string;
  28. };
  29. filenamify.path = (filePath, options) => {
  30. filePath = path.resolve(filePath);
  31. return path.join(path.dirname(filePath), filenamify(path.basename(filePath), options));
  32. };
  33. module.exports = filenamify;
  34. module.exports.default = filenamify;