How to check if two paths are the same in npm?

Viewed 1002

In npm path module, people use path.join because it handles cross platform slashes and extra slashes. However, is there a way to compare two paths to see if its the same folder in a cross platform way?

I want to avoid situations where it ends up comparing /foo/bar to \foo\bar and says its not the same but it really is.

Thanks

2 Answers

The other answer doesn't take into account that paths on win32, unlike most other platforms, are case-insensitive. The following should do the trick:

function pathsAreEqual(path1, path2) {
  path1 = path.resolve(path1);
  path2 = path.resolve(path2);
  if (process.platform == "win32")
    return path1.toLowerCase() === path2.toLowerCase();
  return path1 === path2;
}

Testing:

path.resolve("C:\\Users\\user") == path.resolve("C:\\Users\\USER") // false
pathsAreEqual("C:\\Users\\user", "C:\\Users\\USER") // true
Related