最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - __dirname is not defined - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Nov 23, 2020 at 8:06 Matt 74.7k11 gold badges169 silver badges166 bronze badges asked Nov 23, 2020 at 6:23 PositiveGuyPositiveGuy 20.2k30 gold badges93 silver badges151 bronze badges 8
  • 2 Did you look at answers to this question here: stackoverflow.com/q/8817423/8483196? – Ankit Commented Nov 23, 2020 at 6:35
  • 1 __dirname is only available in script files save with .js ext – Ankit Commented Nov 23, 2020 at 6:36
  • this is a js file, it's expressjs. cloud.google.com/functions/docs/concepts/exec – PositiveGuy Commented Nov 23, 2020 at 6:58
  • I should be at least able to do console.log(__dirname); – PositiveGuy Commented Nov 23, 2020 at 7:00
  • would really like to see the error stack. Can you post it? – Ankit Commented Nov 23, 2020 at 7:00
 |  Show 3 more comments

2 Answers 2

Reset to default 14

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

    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

发布评论

评论列表(0)

  1. 暂无评论