Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 246
Dominus Vilicus Avatar asked Dec 16 '18 04:12

Dominus Vilicus


People also ask

How do I change the path of a node js file?

js: var fs = require('fs') var newPath = "E:\\Thevan"; var oldPath = "E:\\Thevan\\Docs\\something. mp4"; exports. uploadFile = function (req, res) { fs. readFile(oldPath, function(err, data) { fs.

What is a POSIX path?

The posixpath( function converts a path and filename into a POSIX path that can be used as a parameter to a shell command. Parameters. This function has one parameter: path – path and filename to be converted. Can be either a standard UNIX path or an HFS path.

What is node path?

Node. js provides you with the path module that allows you to interact with file paths easily. The path module has many useful properties and methods to access and manipulate paths in the file system. The path is a core module in Node.

How do I find the path of a node?

The first method to get the path of the current directory is the __dirname method. This is a Node. js core module that gets the current path of whatever directory the JavaScript file or module is running in. And you can also get the same result by using the path.


1 Answers

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.

like image 151
Mike 'Pomax' Kamermans Avatar answered Oct 14 '22 03:10

Mike 'Pomax' Kamermans