Skip to content

Change the File Extension in Typescript - Using Path

April 28th, 2017 - SoftwareTutorial(1 min)

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.

Share on
Reddit
Linked in
Whatsapp

A little experiment: