[SOLVED] ENOENT Error, Path undefined, syscall fopen

Next time when posting code on the forums please post code formatted using the integrated code highlighting.
image

Most likely your error is ocurring during either of these lines:

 fs.writeFileSync(`./output/${filename}`, canvas.toBuffer(filetype));
    fs.readFile(`./output/${id}.png`, (err, data) => {

      if (err) rej();

      ipfsArray.push({

        path: `images/${paddedHex}.png`,

        content: data.toString("base64"),

      });

Since the error gives some hint about ā€˜fopen’ I suppose it’s rather the read one than the write one.
This line here:

  fs.readFile(`./output/${id}.png`, (err, data) => {

Using methods such as Crypto Kid provided, try either logging the path to the console.

console.log(`./output/${id}.png`);

If the path returned is the correct one, try using an absolute path and check if the error persists.

1 Like

Thanks, I’ll make sure to post code correctly next time. I rarely ever use forums so I need to get used to this.

As for the code you pointed out, that very well could be the case, but it wouldn’t make sense considering those are ā€œ./output/ā€ commands telling the file where to save the NFTs after they’re created. The ā€œ./inputā€ folder is where all my layers go that canvas is supposed to pull from to use to whip up an NFT and then send it to the ā€œ./output/ā€ folder. The Problem is I can’t eve get to that step if the program can’t even create the NFTs in the first place let alone ā€œoutputā€ them. Even the comment right above the lines of code you pasted says ā€œ// save locally as a fileā€ denoting that these are save functions. I could be completely brain dead about this though.

I did paste in that code ā€œconsole.log(./output/${id}.png);ā€ to see what it returns however and I got this

Mutating 1 of 10000
- rarity: rare
- dna: 01--03-04-01-02-07-03-04-03
C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:450
console.log(`./output/${id}.png`);
                        ^

ReferenceError: id is not defined
    at Object.<anonymous> (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:450:25)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

Node.js v17.1.0
PS C:\Users\Eli\Documents\moralis-mutants-nft-engine-main> 

Also what do you mean by try using absolute path, how would I do that and where would I input it? Remember, think of me as having the IQ of a rock. I need detailed instructions. What you might take for grated as being a given is important to someone like me who’s primarily an artist, 3d modeler, not a programmer.

I did take a stab at it however, modified the line of code to this -

fs.readFile(`C:/Users/Eli/Documents/moralis-mutants-nft-engine-main/output/${id}.png`, (err, data) => {

However nothing changed, still having the same ENOENT, no such file or directory ā€˜undefined’ error.

The error still pops up because the id variable is undefined, thus resulting the error. You use ` for being able to use stuff like ${id} but that kinda breaks up the code highlighting utility. The code is hard to read. Upload the relevant code to pastebin.com and link the paste here.

1 Like

I’m not the one who coded ${id} into this. This is code straight from the Moralis team, almost near bone stock straight from github. This the original Moralis video where I found the code from.

Generate NFTs with this simple code (this could make you millions) PART 1 (by Ash Beech from Moralis)

He doesn’t mention anything about changing ${id} in any of the videos. That’s why I’m here because he glosses over a few things in the video and doesn’t mention any remedies for possible errors, especially this ā€œundefinedā€ error. If you watch this video you’ll have a complete idea of what I’ve done to the code (nearly nothing) and yet mine doesn’t work, but his does. again, the whole code is straight from Ash Beech’s Moralis github.

Here’s the full stock code for the Index.js file from Github, you can scroll through it there. The only lines I’ve changed are the few lines he says to change in the video. (the video is short, it’s like 15min).

https://github.com/ashbeech/moralis-mutants-nft-engine/blob/main/index.js

What keeps sticking out to me is this one line that points to some kind of issue with a canvas file called image.js, specifically line 91.

When I execute ā€œnode index.jsā€ and I get this

PS C:\Users\Eli\Documents\moralis-mutants-nft-engine-main> node index.js
##################
# Generative Art #
# - Generating your NFT collection
##################

-----------------
Mutating 1 of 10000
- rarity: rare
- dna: 01--03-03-02-02-07-03-04-04
C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\node_modules\canvas\lib\image.js:91
  SetSource.call(img, src);
            ^

Error: ENOENT, No such file or directory 'undefined'
    at setSource (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\node_modules\canvas\lib\image.js:91:13)
    at Image.set (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\node_modules\canvas\lib\image.js:62:9)
    at C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\node_modules\canvas\index.js:34:15
    at new Promise (<anonymous>)
    at C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:83:25
    at new Promise (<anonymous>)
    at loadLayerImg (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:82:10)
    at C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:344:29
    at Array.forEach (<anonymous>)
    at saveFile (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:343:15)
    at handleFinal (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:389:31)
    at startCreating (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:392:11)
    at Object.<anonymous> (C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\index.js:448:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) {
  errno: 2,
  code: 'ENOENT',
  path: 'undefined',
  syscall: 'fopen'
}

See at the top, right after the ā€œ-dnaā€¦ā€ line where it points to this line of code that says

C:\Users\Eli\Documents\moralis-mutants-nft-engine-main\node_modules\canvas\lib\image.js:91
  SetSource.call(img, src);
            ^

It’s pointing to the ā€œcallā€ function in line 91.

I tried debugging the whole program all night and sure enough that’s where it breaks. I looked into the image.js file that it’s referencing, but I don’t know how to fix it.

This is the code for the image.js file in Canvas. The line ā€œSetSource.call(img, src);ā€ is all the way at the bottom. 3rd to last line of code.

'use strict';

/*!
 * Canvas - Image
 * Copyright (c) 2010 LearnBoost <[email protected]>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

const bindings = require('./bindings')
const Image = module.exports = bindings.Image
const util = require('util')

// Lazily loaded simple-get
let get;

const {GetSource, SetSource} = bindings;

Object.defineProperty(Image.prototype, 'src', {
  /**
   * src setter. Valid values:
   *  * `data:` URI
   *  * Local file path
   *  * HTTP or HTTPS URL
   *  * Buffer containing image data (i.e. not a `data:` URI stored in a Buffer)
   *
   * @param {String|Buffer} val filename, buffer, data URI, URL
   * @api public
   */
  set(val) {
    if (typeof val === 'string') {
      if (/^\s*data:/.test(val)) { // data: URI
        const commaI = val.indexOf(',')
        // 'base64' must come before the comma
        const isBase64 = val.lastIndexOf('base64', commaI) !== -1
        const content = val.slice(commaI + 1)
        setSource(this, Buffer.from(content, isBase64 ? 'base64' : 'utf8'), val);
      } else if (/^\s*https?:\/\//.test(val)) { // remote URL
        const onerror = err => {
          if (typeof this.onerror === 'function') {
            this.onerror(err)
          } else {
            throw err
          }
        }

        if (!get) get = require('simple-get');

        get.concat(val, (err, res, data) => {
          if (err) return onerror(err)

          if (res.statusCode < 200 || res.statusCode >= 300) {
            return onerror(new Error(`Server responded with ${res.statusCode}`))
          }

          setSource(this, data)
        })
      } else { // local file path assumed
        setSource(this, val);
      }
    } else if (Buffer.isBuffer(val)) {
      setSource(this, val);
    }
  },

  get() {
    // TODO https://github.com/Automattic/node-canvas/issues/118
    return getSource(this);
  },

  configurable: true
});

// TODO || is for Node.js pre-v6.6.0
Image.prototype[util.inspect.custom || 'inspect'] = function(){
  return '[Image'
    + (this.complete ? ':' + this.width + 'x' + this.height : '')
    + (this.src ? ' ' + this.src : '')
    + (this.complete ? ' complete' : '')
    + ']';
};

function getSource(img){
  return img._originalSource || GetSource.call(img);
}

function setSource(img, src, origSrc){
  SetSource.call(img, src);
  img._originalSource = origSrc;
}

it looks like loadLayerImg function maybe fails to load a specific image file

1 Like

That’s what’s confusing to me. All the images are separated in their respective files inside the input folder which is what the instructions say. For example ./input/Background, ./input/Base_head, ,/input/Headgear, etc. And in every folder they’re further separated by rarity folders i.e. ā€œcommon, uncommon, rareā€¦ā€ etc. Every image is a 4320x4320px .png file. Could it be an image resolution issue? Are the images somehow too big? How do I fix it?

you added new images there in those folders from the original tutorial?

1 Like

WOW…can you believe I tried testing the image resolution thing by replacing all the 4320x4320px image files with 1000x1000px image files and sure enough the program started printing out NFTs?? Apparently the program can’t handle images that large. Is that normal, or is there some part of the code itself that can be changed to allow it to work with larger image files? I’m asking because all my image layers are large and I’d have to somehow figure out how to downsize them all.

Also yes, I have all my image layers needed for my own original NFT collection. I replaced all the original project images with my own original artwork.

maybe it is a limitation in the library that tries to process those images
It is good to know that at least now it works for 1000x1000px resolution
you could try 2000x2000px to see if it works

1 Like

Yeah that sounds like possibility. I’m going to try upping the resolution to 2k x 2k and then flat 4k x 4k and see if it still works. I’ll get back in a bit to update you.

This is even more surprising. So what I did this time was copy all my original 4320x4320px images into another folder as a backup. I then went into the input file, deleted all the layer folders, went back to copy my original 4320x4320px images and their respected folders and then pasted them back into the input file…sure enough it’s now printing 4320x4320px NFTs…This is so weird. So the fix all this time was backup the input layer image folders into a different spot, delete the layer files in the input folder, and then copy, re-paste the backup files back into the input folder, or maybe it was getting the program to run with the 1000x1000px image files first which fixed something in the program that enabled it to print the original files…I don’t know if it was the chicken or the egg, but it’s definitely pumping out 4320x4320px NFT images now which was what I originally had in there to begin with. Crazy how it took this long to find such a simple fix that had nothing to do with the code or defining a directory which was what the error originally said was the issue.

The images might have became corrupt for whatever reason.

1 Like

Actually it’s giving me the error again because I didn’t notice I mixed in some 4000x4000px images with the 4320x4320px images so it’s not conclusive yet. It’s definitely printing out 4320px files, but I’m not sure if it’s actually reading 4320px files, or maybe if it has to do with the actual file sizes somehow. I do think it has something to do with the images being corrupted though. I’m going to tinker a bit more. I’ll give an update after I’m done.

Yes! I found the culprit and this is now fixed! So what was happening was, in one of my layer folders for ā€œBase_headā€ I had 5 folders for the 5 different rarity levels, however I only have 2 base head options so I had an image in ā€œcommonā€, an image in ā€œlegendaryā€ and left the other 3 rarity folders empty for the ā€œBase_headā€ layer since I had no other base heads. I thought it didn’t matter if a folder for a certain layer rarity was empty. So I tested to see if that was an issue by filling the other 3 rarity folders with the same image for the ā€œcommonā€ rarity ā€œbase headā€ -> so rarities ā€œcommon, uncommon, rare, and super_rareā€ get the same image and then I kept the 2nd image in the legendary rarity folder. This seems to fix it, I can now use all the original 4320x4320px images and their respective folders and it’s pumping out NFTs again at that resolution.

In short, if you have your layer folders, with various rarity folders in each of them, then you need to make sure you have at least one image in every folder. You can’t leave any folder empty or else it won’t run due to not being able to find an image in said folder.

1 Like

Hi Eli, thanks for posting the issue here. I was facing a similar problem and managed to resolve the issue through this thread.

I have however 2 more problems, I wonder if you faced these or if you or anyone can help with these. (Sorry I’m new to coding ).

  • My first problem is that I’m not getting any JS file corresponding to each image

  • My second problem is that I get an error regarding the Moralis APIKey, which I assume is the reason I’m not getting any links to the images that were generated and there are no files on my Moralis server. The error says:

C:\Users\user\Desktop\moralis-mutants-nft-engine-main\index.js:83
apiKey,
^

ReferenceError: apiKey is not defined
at startCreating (C:\Users\user\Desktop\moralis-mutants-nft-engine-main\index.js:83:5)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

The error refers to Line 83 which is about API Url. Where do I get the API URL?

Thanks!

You may need to put an url for api url and not an api key, but somewhere you should also put the api key

Thanks cryptokid. Just managed to get it working. I found the URL and the corresponding xAPI

1 Like