RaceBase
RaceBase

Reputation: 18848

Normalizing the Paths in NodeJS

I am trying to normalize the paths in NodeJS, so that irrespective of user input (*nix/windows), the path should be accessible by node path.

Ex: c:/test/test.xml
    c:\\test\test.xml
    c:\test/test.xml
    /usr/var/test.xml
    /usr/var\test.xml

These should be normalized so that path lib can access them. I tried using path.normalize on the input /usr/var\test.xml, it didn't work. the output path string is same as input instead of /usr/var/test.xml

Upvotes: 0

Views: 508

Answers (1)

RaceBase
RaceBase

Reputation: 18848

I have written myself simple function to achieve this

export function pathToNix(pathStr: string) {
     var p = path.normalize(pathStr);
     var path_regex = /\/\//;
     p = p.replace(/\\/g, "/");
     while (p.match(path_regex)) {
         p = p.replace(path_regex, "/");
     }
     return p;
}

To clarify few things - Windows supports *nix type file structure (c:/test/a.txt). Thus converted all paths to *nix format.

Upvotes: 1

Related Questions