Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eslint complains about __dirname not being defined in a NodeJS file

Tags:

eslint

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:

  • Alternative for __dirname in Node.js when using ES6 modules
  • __dirname is not defined in nodejs
like image 935
PatS Avatar asked Sep 05 '25 03:09

PatS


2 Answers

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.

like image 143
GOTO 0 Avatar answered Sep 07 '25 20:09

GOTO 0


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

like image 21
joecullin Avatar answered Sep 07 '25 21:09

joecullin