__dirname is not working in node js with webpack bundling Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of __dirname is not working in node js with webpack bundling without wasting too much if your time.

The question is published on by Tutorial Guruji team.

My current directory is

D:bkpProgrammingTestWorksnodejstestApp

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:viewsindex.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.

Answer

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/

We are here to answer your question about __dirname is not working in node js with webpack bundling - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji