15

My current directory is

D:\bkp\Programming\TestWorks\nodejs\testApp

but when i am using __dirname and trying to show a file with express server it gives me this error

Error: ENOENT: no such file or directory, stat 'D:\views\index.html'

my code for that is

res.sendFile(__dirname + 'views/index.html');

when i am bundling it with webpack and run the bundle file then this happens. Otherwise if i just run the normal app.js file it works fine. Help would be appreciated.

mscdex
  • 104,356
  • 15
  • 192
  • 153
ShocKwav3_
  • 1,670
  • 6
  • 22
  • 44

3 Answers3

23

This is because webpack can handle __dirname (and other node specific things) in different ways. If you want it to behave like normal, use this in your webpack config:

{
    node: {
        __dirname: false
    }
}

See: https://webpack.js.org/configuration/node/

0xRm
  • 1,259
  • 8
  • 11
  • Some of the google client libs are requiring dirname to be set to true in webpack.config. But for reading mail templates from the file system, i would like dirname to be the output dir. Is there a way to set it only for some node modules? My cur workaround is using process.cwd() and then /dist for the output dir. But i do not really like that – juliushuck Apr 05 '21 at 16:16
12

The __dirname is set to / by webpack, that's why you end up with /views/index.html which is the root of your file system, that happens to be D:\ in your case. You can set node.dirname to false in your webpack config to not inject it and defer it to runtime. Keep in mind that __dirname will refer to the location of the script you're executing, that means the location of the bundle, not the original source.

node: {
  __dirname: false
}
Michael Jungo
  • 31,583
  • 3
  • 91
  • 84
3

"webpack": "^5.24.4" the default value depends on the target configuration property:

target: 'web' => __dirname = '/'

target: 'node' => __dirname = 'the full path of the output directory'

It can be adjusted using node configuration property, see https://webpack.js.org/configuration/node/#node__dirname

tananyGeek
  • 429
  • 4
  • 4