javascriptnode.jswindowsposix

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

  • 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