4

I don't understand why my Google Cloud Run instance doesn't know what __dirname is

I have an expressjs server that has this in it:

import path from 'path';

const App = express()
    .get('/*', (_req, res) => {
      res.sendFile(path.join(__dirname, '.', 'index.html'));
    })

I get a compile error __dirname is not defined

Matt
  • 68,711
  • 7
  • 155
  • 158
PositiveGuy
  • 17,621
  • 26
  • 79
  • 138

2 Answers2

11

Rename to __dirname it should be point to path.join(__dirname, './src'), or you can create using const __dirname = path.resolve(path.dirname(''));

Geoffrey Hale
  • 10,597
  • 5
  • 44
  • 45
1
    const path = require('path');
     
    import { fileURLToPath } from 'url'
    
    const __filenameNew = fileURLToPath(import.meta.url)
    
    const __dirnameNew = path.dirname(__filenameNew)

you can use __dirnameNew instead of __dirname in ES module

cyan
  • 11
  • 2
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 05 '23 at 14:41