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'
?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With