Node: path.resolve outputs wrong directory on Windows 10

Created on 9 Aug 2017  路  3Comments  路  Source: nodejs/node

I noticed that webpack outputted my bundle on the wrong directoy, so I tried to find the issue and could reproduce a wrong path.resolve as seen in my example below

  • Version: 6.11.1
  • Platform: Windows 10 64-Bit
  • Subsystem: path

When I run the following three lines of code, I don't get the out I expect:

// content of testing.js
const path = require('path');
console.log('you are here', __dirname);
console.log('want to go here', path.resolve (__dirname, '/public') );

output:

d:\Projekte\testing
node testing.js
> you are here d:\Projekte\testing
> want to go here d:\public

output expected:

d:\Projekte\testing
node testing.js
> you are here d:\Projekte\testing
> want to go here d:\Projekte\testing\public

Could not reproduce it in REPL since __dirname is not available there.

path question

Most helpful comment

The documentation for path.resolve() says:

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz.

Given that, the behavior here is working as intended since the right-most argument is already an absolute path ('/public' has a leading slash).

What you want instead is probably something like path.join(__dirname, 'public'), which will return what you are expecting.

All 3 comments

The documentation for path.resolve() says:

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz.

Given that, the behavior here is working as intended since the right-most argument is already an absolute path ('/public' has a leading slash).

What you want instead is probably something like path.join(__dirname, 'public'), which will return what you are expecting.

wow am I stupid... Now I wasted someones time because I didn't notice this. Sorry for that. Of course the resolve is right. Missed to leave the slash

Now I wasted someones time because I didn't notice this. Sorry for that. Of course the resolve is right. Missed to leave the slash

@ellogwen don't berate yourself. It's an honest mistake, and I'm sure everyone is happy this could be resolved so quickly :wink:

Was this page helpful?
0 / 5 - 0 ratings