'Instead change the require of index.js, to a dynamic import() which is available in all CommonJS modules

Trying to work with node/javascript/nfts, I am a noob and followed along a tutorial, but I get this error:

error [ERR_REQUIRE_ESM]: require() of ES Module [...] is not supported. Instead change the require of index.js [ in my file...]  to a dynamic import() which is available in all CommonJS modules

My understanding is that they've updated the node file, so i need a different code than that in the tutorial, but i don't know which one I'm supposed to change, where and to what. Please be as specific as you can

const FormData = require('form-data');
const fetch = require('node-fetch');
const path = require("path")
const basePath = process.cwd();
const fs = require("fs");

fs.readdirSync(`${basePath}/build/images`).foreach(file).forEach(file => {
    const formData = new FormData();
    const fileStream = fs.createReadStream(`${basePath}/build/images/${file}`);
    formData.append('file',fileStream);

    let url = 'https://api.nftport.xyz/v0/files';

    let options = {
      method: 'POST',
      headers: {
        Authorization: '[...]',
      },
      body: formData
    };
    
    fetch(url, options)
      .then(res => res.json())
      .then(json => {
       const fileName = path.parse(json.file_name).name;
       let rawdata = fs.readFileSync(`${basePath}/build/json/${fileName}.json`);
       let metaData = JSON.parse(rawdata);

       metaData.file_url = json.ipfs_url;

       fs.writeFileSync(`${basePath}/build/json${fileName}.json`, JSON.stringify(metaData, null, 2));

       console.log(`${json.file_name} uploaded & ${fileName}.json updated!`);
      })
      .catch(err => console.error('error:' + err));
})



Solution 1:[1]

It is because of the node-fetch package. As recent versions of this package only support ESM, you have to downgrade it to an older version [email protected] or lower.

npm i [email protected]

This should solve the issue.

Solution 2:[2]

I had this error on common.js in angular-devkit after upgrading to angular 13. I found that this is missed during the upgrade:

ng update does not check or update @angular-devkit packages

I got rid of it using:

ng update @angular-devkit/build-angular 

Solution 3:[3]

Go to your package.json file and write

"type": "module",

above debug.

and istead of writing require('chalk') in js file change it to import chalk from 'chalk'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ABDULLOKH MUKHAMMADJONOV
Solution 2 Ger
Solution 3 Leonardo Alves Machado