Suresh Kota
Suresh Kota

Reputation: 315

array length in node.js

I have form object returned from angular js to node js which looks like this in console,

for two files,

filenames : [object Object],[object Object] # filenames object for two files
length: 2 # used object.length

for one file,

filenames : [object Object] # filenames object for one file
length: undefined # used object.length

I am new to Node js, Can anybody please explain me why like this?

Edited

ProfileController.js(client side)

var fd = new FormData()
var filenames = $scope.postTextOrImageParams.imageUrl;
for( var i = 0; i < filenames.length; i++ ) {
     fd.append("imageData",$scope.postTextOrImageParams.imageUrl[i]);  
}

user.js(server side)

var filenames = req.files.imageData;
console.log(typeof filenames);   //-> object
console.log('filenames : '+filenames);
console.log('length: '+filenames.length); 


 function uploader(i) {

 if( i < filenames.length ) { 
         utils.saveMediaPic(filenames[i],function(error,savedImagePath){
      if( error ) {
          console.log('error: '+error)
       }
      else {
          console.log("SAVED IMAGE ====>"+savedImagePath);
          post.content.imageUrl.push(savedImagePath);

          uploader(i+1)
          }
    });
}

Upvotes: 2

Views: 489

Answers (1)

B3rn475
B3rn475

Reputation: 1057

If in the body you have more than one parameter with the same name the bodyParser will generate an array. You problem is that when you have only one perameter it is not so.

In order to force so, you can use the bodyParser in the extended version.

app.use(bodyParser.urlencoded({ extended: true }));

and call the parameter with the squared brackets imageData[]

fd.append("imageData[]",... 

As you can find in the documentation http://npmjs.com/package/qs#readme

This will trigger the extended parser to always return an array.

Upvotes: 1

Related Questions