node.jswindowswebpackabsolute-path

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'?


Solution

  • 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