17

I've just started using eslint. I initialized it and started fixing problems it pointed out. One problem, however, it shouldn't complain about:

const data = fs.readFileSync(path.join(__dirname, _FILENAME));

The error is:

error  '__dirname' is not defined

I did some searching and found that when you add --experimental to the node command that __dirname is not defined. This, however, isn't the case for me. I'm not running node with the --experimental flag.

See these questions:

RobC
  • 22,977
  • 20
  • 73
  • 80
PatS
  • 8,833
  • 12
  • 57
  • 100

2 Answers2

34

This is happening because ESLint does not know that your code is supposed to be used in Node.js: __dirname is not defined in browsers and also not defined in ES modules. To tell ESLint that your code will run in Node.js as a CommonJS module, open your ESLint config and set node: true in the env section. If you are using .eslintrc.json:

{
    "env": {
        "node": true
    }
}

There are also other ways to specify environments, they are explained in the related documentation.

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • 4
    That is (to me) strange because when I ran `npm init @eslint/config`, I selected **NodeJS** as the runtime environment. I'm not sure why **browser** was selected. When I deleted `browser: true` and put in `node: true`, the problem went away. Thank you. – PatS Feb 01 '22 at 14:01
  • Apparently when using `npm init @eslint/config` we need to choose between browser or node by pressing the letter `i` to change the option instead of navigating with arrows. – abhiramd Jun 28 '23 at 07:06
6

I ran into the same. Adding this to .eslintrc.json fixed it for me:

"globals": {
    "__dirname": true
}

Got the idea from this similar question about the process global: https://stackoverflow.com/a/56777068/936907

joecullin
  • 626
  • 1
  • 4
  • 8
  • I think this one is more reasonable since some projects have default global variables and this is the way to tell the Eslint which should be allowed. Thanks – Nguyễn Anh Tuấn Dec 26 '22 at 04:02