The accepted answer doesn't actually answer the question most people come here for.
If you're looking to normalize all path separators (possibly for string work), here's what you need.
All the code segments have the node.js built-in module path
imported to the path
variable.
They also have the variable they work from stored in the immutable variable str
, unless otherwise specified.
If you have a string, here's a quick one-liner normalize the string to a forward slash (/):
const answer = path.resolve(str).split(path.sep).join("/");
You can normalize to any other separator by replacing the forward slash (/).
If you want just an array of the parts of the path, use this:
const answer = path.resolve(str).split(path.sep);
Once you're done with your string work, use this to create a path able to be used:
const answer = path.resolve(str);
From an array, use this:
// assume the array is stored in constant variable arr
const answer = path.join(...arr);
global.__base = __dirname + '/';
. I am willing to change that as that happens only once in the code – Peter/
as the separator inapp/models/article
. I don't know whether or notC:\Something\Something/apps/models/article
works on Windows (I never develop for it), butpath.join(__dirname, 'app', 'models', 'article')
does. – Pember