Search code examples
eslint

eslint complains about __dirname not being defined in a NodeJS file


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:


Solution

  • 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.