Megh Parikh
Megh Parikh

Reputation: 964

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

Upvotes: 44

Views: 82775

Answers (10)

KitaPDev
KitaPDev

Reputation: 36

To force the use of forward slashes, instead of path, you can use path.posix.

For example,

import path from "path";

const pathSegments = ["a/b", "c", "d/e/f"];

console.log(path.posix.join(...pathSegments)); // a/b/c/d/e/f
console.log(path.posix.resolve(...pathSegments)); // /a/b/c/d/e/f

Upvotes: 0

Arul
Arul

Reputation: 1179

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

Upvotes: 1

Ajith Moni
Ajith Moni

Reputation: 19

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";

Upvotes: -1

Miroslav Jonas
Miroslav Jonas

Reputation: 6627

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

Upvotes: 1

Nicolas
Nicolas

Reputation: 225

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);

Upvotes: 10

White Ozil
White Ozil

Reputation: 3

Use path module

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

Upvotes: -1

Vikas Bansal
Vikas Bansal

Reputation: 11750

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

Upvotes: 55

apet
apet

Reputation: 1098

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');
} 

Upvotes: 33

Megh Parikh
Megh Parikh

Reputation: 964

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)

Upvotes: 3

Amadan
Amadan

Reputation: 198324

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);
  }
})();

Upvotes: 0

Related Questions