index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*jshint node:true*/
  2. 'use strict';
  3. /**
  4. * Replaces characters in strings that are illegal/unsafe for filenames.
  5. * Unsafe characters are either removed or replaced by a substitute set
  6. * in the optional `options` object.
  7. *
  8. * Illegal Characters on Various Operating Systems
  9. * / ? < > \ : * | "
  10. * https://kb.acronis.com/content/39790
  11. *
  12. * Unicode Control codes
  13. * C0 0x00-0x1f & C1 (0x80-0x9f)
  14. * http://en.wikipedia.org/wiki/C0_and_C1_control_codes
  15. *
  16. * Reserved filenames on Unix-based systems (".", "..")
  17. * Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1",
  18. * "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  19. * "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", and
  20. * "LPT9") case-insesitively and with or without filename extensions.
  21. *
  22. * Capped at 255 characters in length.
  23. * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs
  24. *
  25. * @param {String} input Original filename
  26. * @param {Object} options {replacement: String}
  27. * @return {String} Sanitized filename
  28. */
  29. var truncate = require("truncate-utf8-bytes");
  30. var illegalRe = /[\/\?<>\\:\*\|":]/g;
  31. var controlRe = /[\x00-\x1f\x80-\x9f]/g;
  32. var reservedRe = /^\.+$/;
  33. var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
  34. var windowsTrailingRe = /[\. ]+$/;
  35. function sanitize(input, replacement) {
  36. var sanitized = input
  37. .replace(illegalRe, replacement)
  38. .replace(controlRe, replacement)
  39. .replace(reservedRe, replacement)
  40. .replace(windowsReservedRe, replacement)
  41. .replace(windowsTrailingRe, replacement);
  42. return truncate(sanitized, 255);
  43. }
  44. module.exports = function (input, options) {
  45. var replacement = (options && options.replacement) || '';
  46. var output = sanitize(input, replacement);
  47. if (replacement === '') {
  48. return output;
  49. }
  50. return sanitize(output, '');
  51. };