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) without any third party code by 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")
// Replace all "this OS's path separator", with the one you need:
const definitelyPosix = somePathString.replaceAll(path.sep, path.posix.sep);
const definitelyWindows = somePathString.replaceAll(path.sep, 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.replaceAll(path.sep, locale.sep);
But of course, you pretty much never need to specifically make a Windows path, because /
has always been a valid path separator in Windows, ever since the very first windows 1.0 days. And if that's news to you as Windows user, try it right now: run cmd
or powershell
and type cd "/Program Files (x86)/Common Files"
, then hit Enter, and observe it changing dirs just fine.
The only time you'll need Windows-specific paths is for absolute paths, as Windows uses drive letters, Linux uses /dev/disk
, and MacOS uses /Volumes
, but 99.9% of the time that you're using absolute paths, what you actually wanted was "relative paths" tacked onto the dir that your entry point file lives in, and the other 0.1% of the time you're trying to load data over the network, using the same path syntax on every OS because that syntax depends on the network protocol you're using.
.replace(/\\/g, '/')
, I already use it in my code. – Rombert