'How can I convert a windows path to posix path using node path
I'm developing on windows, but need to know how to convert a windows path (with backslashes \
) into a POSIX path with forward slashes (/
)?
My goal is to convert C:\repos\vue-t\tests\views\index\home.vue
to C:/repos/vue-t/tests/views/index/home.vue
so I can use it in an import on a file I'm writing to the disk
const appImport = `
import Vue from "vue"
import App from '${path}'
function createApp (data) {
const app = new Vue({
data,
render: h => h(App)
})
return app
}`
//this string is then written to the disk as a file
I'd prefer not to .replace(/\\/g, '/')
the string, and would rather prefer to use a require('path')
function.
Solution 1:[1]
Slash converts windows backslash paths to Unix paths
Usage:
const path = require('path');
const slash = require('slash');
const str = path.join('foo', 'bar');
slash(str);
// Unix => foo/bar
// Windows => foo/bar
Solution 2:[2]
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) using Node's standard library path module, and more specifically, taking advantage of its dedicated path.posix and path.win32 namespaced properties/functions (introduced in Node v0.11):
const path = require("path");
// ...
const definitelyPosix = somePathString.split(path.sep).join(path.posix.sep);
This will convert your path to POSIX format irrespective of whether you're already on a POSIX compliant platform, or on win32, without needing any kind of external dependency.
Solution 3:[3]
There is node package called upath will convert windows path into unix.
upath = require('upath');
or
import * as upath from 'upath';
upath.toUnix(destination_path)
Solution 4:[4]
For those looking for an answer that doesn't depend on Node.js
One Liner (no 3rd party library)
//
// one-liner
//
let convertPath = (windowsPath) => windowsPath.replace(/^\\\\\?\\/,"").replace(/\\/g,'\/').replace(/\/\/+/g,'\/')
//
// usage
//
convertPath("C:\\repos\\vue-t\\tests\\views\\index\\home.vue")
// >>> "C:/repos/vue-t/tests/views/index/home.vue"
//
// multi-liner (commented and compatible with really old javascript versions)
//
function convertPath(windowsPath) {
// handle the edge-case of Window's long file names
// See: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#short-vs-long-names
windowsPath = windowsPath.replace(/^\\\\\?\\/,"");
// convert the separators, valid since both \ and / can't be in a windows filename
windowsPath = windowsPath.replace(/\\/g,'\/');
// compress any // or /// to be just /, which is a safe oper under POSIX
// and prevents accidental errors caused by manually doing path1+path2
windowsPath = windowsPath.replace(/\/\/+/g,'\/');
return windowsPath;
};
// dont want the C: to be inluded? here's a one-liner for that too
let convertPath = (windowsPath) => windowsPath.replace(/^\\\\\?\\/,"").replace(/(?:^C:)?\\/g,'\/').replace(/\/\/+/g,'\/')
Normally I import libraries. However, I went and read the source code for both slash
and upath
. The functions were not particularly up to date, and incredibly small at the time I checked. In fact, this one liner actually handles more cases than the slash library. Not everyone is looking for this kind of solution, but for those that are, here it is. By coincidence this has the fastest runtime of all the current answers.
Solution 5:[5]
Just use default lib as:
const {direname, resolve, basename}= require('path').posix;
or
import {posix} from 'path';
const {direname, resolve, basename}= posix;
Solution 6:[6]
I was looking for something similar, but a little more universal especially to include drives in the absolute path. Thus if you work with e.g. git-bash or WSL usually drives are mapped by default as letters from root / (git-bash) or /mnt (WSL). So here is a regex that does the job for me
// For git-bash Windows drives are mounted in the root like /C/ /D/ etc.
const toGitBashPosixPath = (windowsPath) => windowsPath.replace(/^(\w):|\\+/g,'/$1');
console.log(toGitBashPosixPath('c:\\\\\\project\\file.x')); // messy Windows path
console.log(toGitBashPosixPath('c:\\project\\file.x')); // regular Windows path
console.log(toGitBashPosixPath('c:/project/file.x')); // slash path acceptable by Windows
console.log(toGitBashPosixPath('project\\file.x'));// relative Windows path
console.log(toGitBashPosixPath('.\\project\\file.x'));// another relative Windows path
// For WSL Windows drives are mounted by default next to /mnt like /mnt/C/ /mnt/D/ etc.
const toWSLPosixPath = (windowsPath) => windowsPath.replace(/^(\w):|\\+/g,'/$1').replace(/^\//g,'/mnt/');
console.log(toWSLPosixPath('c:\\project\\file.x'))
Hopefully this will help someone.
Solution 7:[7]
Here is a solution that returns the module directory in a platform agnostic way, which works with "type": "module"
:
const path = require('path');
const getModuleDir = (moduleName) => {
const entry = require.resolve(moduleName);
const entryPosix = entry.split(path.sep).join(path.posix.sep);
return path.resolve(entryPosix.split(moduleName)[0] + moduleName);
};
Explanation:
Let's assume we want the folder path for a module named @foo/bar
.
- Find the entry point of the module using
require.resolve
. This may point to a file deeply nested in the module:- Example posix:
/home/joe/node_modules/@foo/bar/bing/baz/index.js
- Example win32:
C:\Users\joe\node_modules\@foo\bar\bing\baz\index.js
- Example posix:
- Convert all slashes to posix style forward slashes (this is needed for windwos).
- Split the posix-friendly path on the module name. You get an array with two items:
- Example posix:
["/home/joe/node_modules/", "/bing/baz/index.js"]
- Example win32:
["C:/Users/joe/node_modules", "/bing/baz/index.js"]
- Example posix:
- Join the first part from Step #3 with the module name, which conveniently converts it back to the platform-specific path:
- Final result posix:
/home/joe/node_modules/@foo/bar
- Final result win32:
C:\Users\joe\node_modules\@foo\bar
- Final result posix:
Note: this will also work if the package is nested inside of another package's node_modules folder. For example, Step #1 might return a path like this:
/home/joe/node_modules/some-package/node_modules/@foo/bar/bing/baz/index.js
This script will still work.
Solution 8:[8]
const winPath = 'C:\\repos\\vue-t\\tests\\views\\index\\home.vue'
const posixPath = winPath.replace(/\\/g, '/').slice(2)
// Now posixPath = '/repos/vue-t/tests/views/index/home.vue'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rajika Imal |
Solution 2 | |
Solution 3 | Mohideen bin Mohammed |
Solution 4 | |
Solution 5 | Khalid Rafik |
Solution 6 | Micha? Grzegorzewski |
Solution 7 | |
Solution 8 | Mustafa |