Psl
Psl

Reputation: 3920

getting multiple images from folder and save image names to json array

Am trying to find the images contianed in a folder. using this code am getting the image with names and total count of the images.

after that i need to save it to a json array.for that

i tried report[tests[0]].screenshot = PNGs[i]; it is working if only one image is found in the folder. if multiple images are found i tried

  report[tests[0]].screenshot +i  =  PNGs[i]; 

but am getting [ReferenceError: Invalid left-hand side in assignment]

common.getFilesInFolder(reportDir, '.png', function(err, PNGs) {
        if(!err && PNGs.length > 0){
          for(var i=0; i< PNGs.length; i++){
            report[tests[0]].screenshot +i  =  PNGs[i]; 

          }
        }
        callback(null, report);
      });

if only one image is found in the folder below code is working fine with out any error

common.getFilesInFolder(reportDir, '.png', function(err, PNGs) {
        if(!err && PNGs.length > 0){         
            report[tests[0]].screenshot =  PNGs[0];
        }
        callback(null, report);
      });

How can i use this code for saving if there is multiple images..

Upvotes: 0

Views: 419

Answers (2)

Gergo Erdosi
Gergo Erdosi

Reputation: 42073

Change that line to:

report[tests[0]]['screenshot' + i] = PNGs[i];

As the message says you can't use expressions that way on the left-hand side of the assignment.

Upvotes: 1

Tiemen
Tiemen

Reputation: 894

The error is (as you may have presumed) caused by this statement:

report[tests[0]].screenshot +i  =  PNGs[i]; 

This part:

report[tests[0]].screenshot

... is a property "screenshot" on an object that exists in report[tests[0]]. You assign a value to it in your working example (PNGs[i]). If the property "screenshot" did not exist yet, it will after this statement, due to the nature of the dynamic object. The value becomes PNGs[i], overwriting the previous value of "screenshot" if it already did exist.

Now where it goes wrong, is the "+ i" part. As soon as you state "report[tests[0]].screenshot", the left hand side of the assignment becomes whatever value lives in "report[tests[0]].screenshot", either null or a previously assigned PNG. So what you actually doing is:

null + i = PNGs(i)

... or if a value already existed:

SomePNGInstance + i = PNGs(i)

... which is not possible because you can only add i to another integer / float, not to an object instance. And then you assign PNGs(i) to null or NaN or whatever the + i statement has evaluated to, (sorry, haven't coded JavaScript in a while - this is a generic coding error) which is an invalid assignment.

Both cases would cause the error you are seeing. I'd advise to just use array.push() to incrementally fill an array with images, or use something like myPNGArray[i] = PNGs(i).

Upvotes: 1

Related Questions