140

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));
})

ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
Basse Nord
  • 1,443
  • 2
  • 3
  • 4
  • I did npm i node-fetch@2.6.1, it seems like it fixed it, then i wrote node utils/nftport/uploadFiles.js in the terminal (dont know the proper terms) and it said "file is not defined" is these problems connected? what wrong did i do? – Basse Nord Dec 31 '21 at 10:33

8 Answers8

142

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 node-fetch@2.6.1 or lower.

npm i node-fetch@2.6.1

This should solve the issue.

ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
  • 11
    how do you know this was the error, I am going mad since last one hour – jeea Jun 08 '22 at 15:19
  • 4
    it is in the documentation: https://www.npmjs.com/package/node-fetch#user-content-commonjsCommonJS node-fetch from v3 is an ESM-only module - you are not able to import it with require(). If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2. `npm install node-fetch@2` – PhilWilliammee Oct 31 '22 at 19:09
  • The instructions by @PhilWilliammee are the way to go as `2.6.1` has an audit warning now. – Mr Rogers Nov 17 '22 at 22:58
  • 4
    2.6.7 also works, frens – mikeDOTexe Nov 19 '22 at 16:58
  • 1
    From [got-install](https://github.com/sindresorhus/got#install), the author writes a convert ESM guide [Pure ESM package](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) might be helpful. – Jun Yu Feb 22 '23 at 08:02
28

No need to use the old version. You can use this line instead of "require"

const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
Itzik
  • 275
  • 2
  • 4
12

Go to your package.json file and write:

"type": "module",

above debug.

and instead of writing require('chalk') in the .js file, change it to import chalk from 'chalk'

Mona Thahmeen
  • 213
  • 1
  • 2
11

This can occur when you install the latest version of a package that has an issue with modules import.

In my case, I was getting the error after installing the latest version of crypto-random-string package. To know which package is causing this error, check the message preceding the above error reported. In my case, it read like so: error: uncaughtException: require() of ES Module /Users/myname/Documents/mydir/anotherdir/my-project/node_modules/crypto-random-string/index.js

To fix it, I only downgraded to an earlier version by doing the following:

  1. yarn remove crypto-random-string
  2. yarn add crypto-random-string@3.3.1
Hameed Damee
  • 281
  • 4
  • 7
4

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 
Ger
  • 169
  • 1
  • 11
1

Another option that worked for me is using the package node-fetch-native that redistributes node-fetch with some polyfill.

David Dal Busco
  • 7,975
  • 15
  • 55
  • 96
0

In your .tsconfig:

change "module": "nodenext", to "module": "commonjs", if your projects allows.

Boern
  • 7,233
  • 5
  • 55
  • 86
-5

I added the one statement extra you can see this "type": "module", statement, written down after license.

"author": "",
  "license": "ISC",
  "type": "module",
  "dependencies": {
    "chalk": "^5.0.1"
    
  }
}
E_net4
  • 27,810
  • 13
  • 101
  • 139