40

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

Megh Parikh
  • 924
  • 2
  • 7
  • 25
  • https://nodejs.org/api/path.html – Amadan Dec 17 '15 at 07:48
  • @Amadan as I said I doont want to change how I require the module – Megh Parikh Dec 17 '15 at 07:50
  • 1
    If you don't want to change your code, what do you expect us to do? – Amadan Dec 17 '15 at 07:52
  • I was talking about alernative way around `global.__base = __dirname + '/';`. I am willing to change that as that happens only once in the code – Megh Parikh Dec 17 '15 at 07:55
  • You are still fixing `/` as the separator in `app/models/article`. I don't know whether or not `C:\Something\Something/apps/models/article` works on Windows (I never develop for it), but `path.join(__dirname, 'app', 'models', 'article')` does. – Amadan Dec 17 '15 at 07:57

8 Answers8

54

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
Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100
  • 3
    @VikasBansat: `path.normalize(path.resolve('./'))` - is effectively the way you suggest. However this does not resolve the issue under Windows 8 (at least). – Valentine Shi Jul 01 '18 at 11:04
  • 45
    This doesn't work, at all. Backslashes remain backslashes. – Andrew Koster Mar 17 '20 at 22:56
  • 1
    This only works for UNIX systems. For Windows, default path delimiter is backslash – Noname Apr 28 '22 at 06:56
  • After testing, this doesn't work on windows. Slashes still remain backward with this. This answer should not be the accepted one, because it doesn't solve the problem for Windows, for which it was asked for. – Vladimir Jovanović Aug 17 '23 at 10:06
27

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');
} 
apet
  • 958
  • 14
  • 16
3

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)

Megh Parikh
  • 924
  • 2
  • 7
  • 25
3

The accepted answer doesn't actually answer the question most people come here for. If you're looking to normalize all path separators (possibly for string work), here's what you need.

All the code segments have the node.js built-in module path imported to the path variable. They also have the variable they work from stored in the immutable variable str, unless otherwise specified.

If you have a string, here's a quick one-liner normalize the string to a forward slash (/):

const answer = path.resolve(str).split(path.sep).join("/");

You can normalize to any other separator by replacing the forward slash (/).

If you want just an array of the parts of the path, use this:

const answer = path.resolve(str).split(path.sep);

Once you're done with your string work, use this to create a path able to be used:

const answer = path.resolve(str);

From an array, use this:

// assume the array is stored in constant variable arr
const answer = path.join(...arr);
Nicolas
  • 135
  • 1
  • 6
1

This is the approach I use, to save some processing:

const path = require('path');

// normalize based on the OS
const normalizePath = (value: string): string {
  return path.sep === '\' 
    ? value.replace(/\\/g, '/')
    : value;
}

console.log('abc/def'); // leaves as is
console.log('abc\def'); // on windows converts to `abc/def`, otherwise leave as is
Miroslav Jonas
  • 5,407
  • 1
  • 27
  • 41
0

I recommend against this, as it is patching node itself, but... well, no changes in how you require things.

(function() {
  "use strict";
  var path = require('path');
  var oldRequire = require;
  require = function(module) {
    var fixedModule = path.join.apply(path, module.split(/\/|\\/));
    oldRequire(fixedModule);
  }
})();
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Windows uses \, Linux and mac use / for path prefixes

For Windows : 'C:\\Results\\user1\\file_23_15_30.xlsx'

For Mac/Linux: /Users/user1/file_23_15_30.xlsx

If the file has \ - it is windows, use fileSeparator as \, else use /

let path=__dirname; // or filePath
fileSeparator=path.includes('\')?"\":"/"  
newFilePath = __dirname + fileSeparator + "fileName.csv";
csgeek
  • 711
  • 6
  • 15
Ajith Moni
  • 21
  • 3
-1

Use path module

const path = require("path");
var str = "test\test1 (1).txt";
console.log(str.split(path.sep)) // This is only on Windows