Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs absolute paths in windows with forward slash

Can I have absolute paths with forward slashes in windows in nodejs? I am using something like this :

global.__base = __dirname + '/'; var Article = require(__base + 'app/models/article'); 

But on windows the build is failing as it is requiring something like C:\Something\Something/apps/models/article. I aam using webpack. So how to circumvent this issue so that the requiring remains the same i.e. __base + 'app/models/src'?

like image 997
Megh Parikh Avatar asked Dec 17 '15 07:12

Megh Parikh


People also ask

How do you use backslash in node js?

When you set the variable, the escaped backslash is interpreted into a single codepoint. However, options is an object which, when logged, appears as a JSON blob. The backslash is re-escaped at this point, as this is the only way the backslash can appear validly as a string value within the JSON output.

What does forward slash mean in path?

For example, backslashes are used in non-relative path C:\Program Files (x86)\Microsoft Office\Office16. Yet, for a relative path, Windows adopts forward slashes. While in Mac, Linux, Android, Chrome, and Steam, all Unix-like operating systems, directories in file paths are separated by forward slashes.

Where is node js path in Windows?

Installation on Windows By default, the installer uses the Node. js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejs\bin directory in window's PATH environment variable.


1 Answers

I know it is a bit late to answer but I think my answer will help some visitors.

In Node.js you can easily get your current running file name and its directory by just using __filename and __dirname variables respectively.

In order to correct the forward and back slash accordingly to your system you can use path module of Node.js

var path = require('path'); 

Like here is a messed path and I want it to be correct if I want to use it on my server. Here the path module do everything for you

var randomPath = "desktop//my folder/\myfile.txt";

var correctedPath = path.normalize(randomPath); //that's that  console.log(correctedPath); 
desktop/my folder/myfile.txt 

If you want the absolute path of a file then you can also use resolve function of path module

var somePath = "./img.jpg"; var resolvedPath = path.resolve(somePath);  console.log(resolvedPath); 
/Users/vikasbansal/Desktop/temp/img.jpg 
like image 135
Vikas Bansal Avatar answered Sep 24 '22 18:09

Vikas Bansal