Skip to content
Advertisement

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

Advertisement

Answer

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.

Advertisement