How can I convert a windows path to posix path using node path

Dominus Vilicus picture Dominus Vilicus · Dec 16, 2018 · Viewed 15.4k times · Source

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.

Answer

Mike 'Pomax' Kamermans picture Mike 'Pomax' Kamermans · Aug 4, 2020

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 POSIX platforms, or on win32, while requiring zero dependencies.