You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*!
  2. * strip-dirs | MIT (c) Shinnosuke Watanabe
  3. * https://github.com/shinnn/node-strip-dirs
  4. */
  5. 'use strict';
  6. const path = require('path');
  7. const util = require('util');
  8. const isNaturalNumber = require('is-natural-number');
  9. module.exports = function stripDirs(pathStr, count, option) {
  10. if (typeof pathStr !== 'string') {
  11. throw new TypeError(
  12. util.inspect(pathStr) +
  13. ' is not a string. First argument to strip-dirs must be a path string.'
  14. );
  15. }
  16. if (path.posix.isAbsolute(pathStr) || path.win32.isAbsolute(pathStr)) {
  17. throw new Error(`${pathStr} is an absolute path. strip-dirs requires a relative path.`);
  18. }
  19. if (!isNaturalNumber(count, {includeZero: true})) {
  20. throw new Error(
  21. 'The Second argument of strip-dirs must be a natural number or 0, but received ' +
  22. util.inspect(count) +
  23. '.'
  24. );
  25. }
  26. if (option) {
  27. if (typeof option !== 'object') {
  28. throw new TypeError(
  29. util.inspect(option) +
  30. ' is not an object. Expected an object with a boolean `disallowOverflow` property.'
  31. );
  32. }
  33. if (Array.isArray(option)) {
  34. throw new TypeError(
  35. util.inspect(option) +
  36. ' is an array. Expected an object with a boolean `disallowOverflow` property.'
  37. );
  38. }
  39. if ('disallowOverflow' in option && typeof option.disallowOverflow !== 'boolean') {
  40. throw new TypeError(
  41. util.inspect(option.disallowOverflow) +
  42. ' is neither true nor false. `disallowOverflow` option must be a Boolean value.'
  43. );
  44. }
  45. } else {
  46. option = {disallowOverflow: false};
  47. }
  48. const pathComponents = path.normalize(pathStr).split(path.sep);
  49. if (pathComponents.length > 1 && pathComponents[0] === '.') {
  50. pathComponents.shift();
  51. }
  52. if (count > pathComponents.length - 1) {
  53. if (option.disallowOverflow) {
  54. throw new RangeError('Cannot strip more directories than there are.');
  55. }
  56. count = pathComponents.length - 1;
  57. }
  58. return path.join.apply(null, pathComponents.slice(count));
  59. };