eslint complains about __dirname not being defined in a NodeJS file
Asked Answered
T

3

24

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:

Trailer answered 1/2, 2022 at 1:53 Comment(4)
Use process.cwd() insteadInstitutor
Also you may check out https://mcmap.net/q/46785/-why-is-__dirname-not-defined-in-node-replInstitutor
Does this answer your question? Why is __dirname not defined in node REPL?Institutor
Won't process.cwd() give the current working directory of the process? Sometimes you want the path of the (possibly included or required) file instead.Mccormac
D
48

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.

Damle answered 1/2, 2022 at 7:18 Comment(2)
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.Trailer
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.George
M
10

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://mcmap.net/q/118360/-eslint-39-process-39-is-not-defined

Mccormac answered 23/3, 2022 at 13:12 Comment(1)
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. ThanksChina
G
1

In 2024 you need globals.node instead. For context, an example eslint.config.mjs follows:

export default [
  pluginJs.configs.recommended,
  {
    files: ['**/*.js'],
    languageOptions: {
      sourceType: 'commonjs',
      globals: { ...globals.node }
    },
    rules: {
      semi: ['error', 'never']
    }
  }
]
Grouping answered 24/7 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.