Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Nodejs: iterate over req.files properties

Nodejs: iterate over req.files properties

Problem

I'm quite new to nodejs and sometimes I come across difficulties :) So for example. I'm sending an image file via AJAX and recieve it successfully in my app.

console.log(req.files) prints:

{
    img_1351078491675: {
        size: 354683,
        path: '/tmp/f29009b6dc914c2ab27e2c5fde13e7d8.jpg',
        name: 'nov10wallpaper-1_1600.jpg',
        type: 'image/jpeg',
        hash: false,
        lastModifiedDate: Wed Oct 24 2012 13: 36: 55 GMT + 0200(CEST),
        _writeStream: {
            path: '/tmp/f29009b6dc914c2ab27e2c5fde13e7d8.jpg',
            fd: 14,
            writable: false,
            flags: 'w',
            encoding: 'binary',
            mode: 438,
            bytesWritten: 354683,
            busy: false,
            _queue: [],
            _open: [Function],
            drainable: true
        },
        length: [Getter],
        filename: [Getter],
        mime: [Getter]
    }
}

Because the image has a timestamp I cannot access with req.files.img_. So I was using for(file in reg.files) to get it (forEach didn't work - no idea why. seems to be a normal hash/object). But now my problems actually start. How can I read out the attributes of that file? E.g. file.path doesn't work. It returns "undefined" but why?

Could someone please give me a hint to understand such basics?

Problem courtesy of: JimBob

Solution

I believe forEach() is meant for arrays rather than objects, so that's probably why that didn't work.

If there is only (ever) one file, then:

var fileKey = Object.keys(req.files)[0];
var file = req.files[fileKey];

...or just:

var file = req.files[Object.keys(req.files)[0]];`

...will 'dig down one level' so you can do file.path or file.type. If there are (or might be) more than one:

var files = [];
var fileKeys = Object.keys(req.files);

fileKeys.forEach(function(key) {
    files.push(req.files[key]);
});

This will give you a list of files 'dug down one level', on which you can forEach().

Hope that helps!

Solution courtesy of: floatingLomas

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Nodejs: iterate over req.files properties

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×