Nodejs absolute paths in windows with forward slash

I finally did it like this:

var slash = require('slash');
var dirname = __dirname;
if (process.platform === 'win32') dirname = slash(dirname);

global.__base = dirname + '/';

And then to require var Article = require(__base + 'app/models/article');. This uses the npm package slash (which replaces backslashes by slashes in paths and handles some more cases)


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

it's 2020, 5 years from the question was published, but I hope that for somebody my answer will be useful. I've used the replace method, here is my code(express js project):

const viewPath = (path.join(__dirname, '../views/')).replace(/\\/g, '/')

exports.articlesList = function(req, res) {
    res.sendFile(viewPath + 'articlesList.html');
}