| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var path = require('path'); |
| 4 | |
| 5 | function replaceExt(npath, ext) { |
| 6 | if (typeof npath !== 'string') { |
| 7 | return npath; |
| 8 | } |
| 9 | |
| 10 | if (npath.length === 0) { |
| 11 | return npath; |
| 12 | } |
| 13 | |
| 14 | var nFileName = path.basename(npath, path.extname(npath)) + ext; |
| 15 | var nFilepath = path.join(path.dirname(npath), nFileName); |
| 16 | |
| 17 | // Because `path.join` removes the head './' from the given path. |
| 18 | // This removal can cause a problem when passing the result to `require` or |
| 19 | // `import`. |
| 20 | if (startsWithSingleDot(npath)) { |
| 21 | return '.' + path.sep + nFilepath; |
| 22 | } |
| 23 | |
| 24 | return nFilepath; |
| 25 | } |
| 26 | |
| 27 | function startsWithSingleDot(fpath) { |
| 28 | var first2chars = fpath.slice(0, 2); |
| 29 | return (first2chars === '.' + path.sep) || |
| 30 | (first2chars === './'); |
| 31 | } |
| 32 | |
| 33 | module.exports = replaceExt; |