Nodejs absolute paths in windows with forward slash

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

Leave a Comment

tech