Nodejs absolute paths in windows with forward slash
Asked Answered
P

9

43

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

Peter answered 17/12, 2015 at 7:42 Comment(5)
nodejs.org/api/path.htmlPember
@Pember as I said I doont want to change how I require the modulePeter
If you don't want to change your code, what do you expect us to do?Pember
I was talking about alernative way around global.__base = __dirname + '/';. I am willing to change that as that happens only once in the codePeter
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.Pember
P
53

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
Pokeweed answered 27/2, 2016 at 11:19 Comment(4)
@VikasBansat: path.normalize(path.resolve('./')) - is effectively the way you suggest. However this does not resolve the issue under Windows 8 (at least).Melodymeloid
This doesn't work, at all. Backslashes remain backslashes.Precedential
This only works for UNIX systems. For Windows, default path delimiter is backslashNeuroma
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.Fife
E
33

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');
} 
Eiffel answered 25/2, 2020 at 13:7 Comment(1)
works nicely for me to insert the forward slashed path into a databaseLoraleeloralie
C
8

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);
Cardwell answered 2/1, 2022 at 23:17 Comment(0)
P
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)

Peter answered 18/12, 2015 at 17:8 Comment(3)
I'd rather recommend using nodejs.org/api/path.html#path_path_sep which is the very purpose of this feature ;) And make it a one-liner!Communicative
@Communicative Thanks for this! Never heard about path.sep before - it was just what is was looking for!Burned
Thanks for reminding me this solution exists, I had completely forgotten about it ^^'Communicative
H
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
Handily answered 18/2, 2022 at 8:44 Comment(0)
S
1

It is already too late but the actual answer is using path.sep or path.join depends on the requirement.

In Windows directory path will be "" and Linux "/" so the path library will do this work automatically.

const path = require("path");
const abPath = path.join(__base ,'app','models','article')

OR

const path = require("path");
const abPath = __base + 'app'+ path.sep +'models'+ path.sep +'article';
Swirl answered 10/9, 2023 at 9:10 Comment(0)
P
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);
  }
})();
Pember answered 17/12, 2015 at 8:5 Comment(0)
M
-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
Monocyte answered 17/11, 2021 at 8:50 Comment(0)
K
-1

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";
Kazantzakis answered 16/8, 2022 at 12:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.