Search code examples
node.jsrequire

'ReferenceError: require is not defined' while importing fs module


I am new to NodeJS. I was importing the 'fs' module in NodeJS and this happened.

enter image description here

Is this because of the new import syntax in the current versions? What went wrong?

Thanks in advance!


Solution

  • This is because something is telling nodejs that this is the newer ESM module. This could be your package.json file or something else. In an ESM module file, you use import, not require() to load modules.

    You can see in the stack trace where it shows Object.loadESM and that's how you know it is trying to load this module as an ESM module.

    With an ESM module, perhaps you want this:

    import fs from "fs";
    

    or

    import * as fs from'fs';
    

    Or, if you intend to use a CommonJS module instead (where you can use require()), then we need to see your package.json file to figure out why the loader is attempting to load your file as an ESM module.