blob: 7a78278257c69b72203e63365cc4639c72d9ba06 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var path = require('path');
4
5function 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
27function startsWithSingleDot(fpath) {
28 var first2chars = fpath.slice(0, 2);
29 return (first2chars === '.' + path.sep) ||
30 (first2chars === './');
31}
32
33module.exports = replaceExt;