Change the File Extension in Typescript - Using Path
1 min read

Change the File Extension in Typescript - Using Path

Change the File Extension in Typescript - Using Path

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:

  1. isolate the dir, ext and root components of the path
  2. replace the ext with the new extension
  3. 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.