Given that all the other answers rely on installing (either way too large, or way too small) third party modules: this can also be done as a one-liner for relative paths (which you should be using 99.999% of the time already anyway) using Node's standard library path
module, and more specifically, taking advantage of its dedicated path.posix
and path.win32
namespaced properties/functions (introduced all the way back in Node v0.11):
import path from "path"; // or in legacy cjs: const path = require("path")
// Split on whatever is "this OS's path separator",
// then explicitly join with posix or windows separators:
const definitelyPosix = somePathString.split(path.sep).join(path.posix.sep);
const definitelyWindows = somePathString.split(path.sep).join(path.win32.sep);
This will convert your path to POSIX (or Windows) format irrespective of whether you're already on a POSIX (or Windows) compliant platform, without needing any kind of external dependency.
Or, if you don't even care about which OS you're in:
import path from "path";
const { platform } = process;
const locale = path[platform === `win32` ? `win32` : `posix`];
...
const localePath = somepath.split(path.sep).join(locale.sep);
And of course, be aware that paths with /
in them have always been valid paths in Windows, ever since the very first windows 1.0 days. So there's not a lot of value in turning Posix paths into Windows paths (manually, at least. If you need absolute paths, Posix and Windows differ drastically in how those are exposed, of course, but pretty much any time you need an absolute path, that's a config value and you should be using .env
files anyway)