Reddy Reddy - 1 year ago 56
Node.js Question

Normalizing the Paths in NodeJS

I am trying to normalize the paths in

, so that irrespective of user input
, the path should be accessible by
node path

Ex: c:/test/test.xml

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

Answer Source

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.