index.js 767 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var path = require('path');
  3. function replaceExt(npath, ext) {
  4. if (typeof npath !== 'string') {
  5. return npath;
  6. }
  7. if (npath.length === 0) {
  8. return npath;
  9. }
  10. var nFileName = path.basename(npath, path.extname(npath)) + ext;
  11. var nFilepath = path.join(path.dirname(npath), nFileName);
  12. // Because `path.join` removes the head './' from the given path.
  13. // This removal can cause a problem when passing the result to `require` or
  14. // `import`.
  15. if (startsWithSingleDot(npath)) {
  16. return '.' + path.sep + nFilepath;
  17. }
  18. return nFilepath;
  19. }
  20. function startsWithSingleDot(fpath) {
  21. var first2chars = fpath.slice(0, 2);
  22. return (first2chars === '.' + path.sep) ||
  23. (first2chars === './');
  24. }
  25. module.exports = replaceExt;