7

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
  • 20,007
  • 20
  • 62
  • 73
PatS
  • 5,912
  • 9
  • 39
  • 72

2 Answers2

7

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
  • 35,223
  • 20
  • 108
  • 138
  • 1
    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
1

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
  • 576
  • 1
  • 3
  • 7