Following from my previous post, I've updated the function to use only the path
module. Now, the code looks like:
export function changeExtension(filepath: string, extension: string): string {
let dir: string = path.dirname(filepath)
let ext: string = path.extname(filepath)
let root: string = path.basename(filepath, ext)
ext = extension.startsWith('.') ? extension : extension.length > 0 ? `.${extension}` : ''
return path.normalize(`${dir}${path.sep}${root}${ext}`)
}
I've updated the workflow presented previously to:
- isolate the
dir
,ext
androot
components of the path - replace the
ext
with the new extension - return the normalized version of the composed path
Now, our function accepts complete paths, not only filenames.
Note: The path.normalize()
function does NOT calculate the absolute path. It only changes the path separators.
Member discussion: