Ask coding questions

← Back to all posts
__dirname not defined on nodejs server
NIghel123 (2)

I was using the variable __dirname on my node server like that:

app.use(express.static(__dirname + '/public'));

but wherever I am using this variable on the server the server gives an error:

ReferenceError: __dirname is not defined
at evalmachine.<anonymous>:22:24
at Script.runInContext (vm.js:74:29)
at Object.runInContext (vm.js:182:6)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:180:13)
at addChunk (_stream_readable.js:274:12)
at readableAddChunk (_stream_readable.js:261:11)
at ReadStream.Readable.push (_stream_readable.js:218:10)
at (fs.js:2124:12)

my repository is:

kpostal10 (31)

two ways to fix this use process.cwd()
or you can fix it via path
const path = require('path'); var __dirname = path.resolve();

RahulChoubey1 (136)

@kpostal10 The former does not work if run from another directory.