How can I convert a windows path to posix path usi

2020-04-04 03:17发布

问题:

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.

回答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


回答2:

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)