How to count how many binaries per item? And, how can I use binary properties in an expression, e.g. mime type or file extension

Hey,

I need help figuring out how to count how many attachment a message from G Mail inbox has, and if it doesn’t have attachments should add a 0.

Also, how can I use binary properties in an expression? I’d like to be able to apply an IF condition based on binary mime type.

Thanks beforehand.

Hi @Mike_M, assuming you are using the current version of n8n, you could count the number of binary items like so for example:

Result:

The number is calculated using Object.keys($input.item.binary).length in the Code node at the end. Object.keys() returns an array of all binary properties of $input.item.binary containing the binary data of an item. .length returns the count.

You can use also use $input.item.binary (or its shorthand form $binary) to read specific properties and apply additional logic to each. You will need to provide the name of the property though if you want to use this in an expression.

Hope this makes sense and helps!

Hey @MutedJam, thanks for the detailed reply!

I tried the code on the output of a GMail node, but I’m getting the following error:

ERROR: Cannot convert undefined or null to object [line 1, for item 0]

Looks like one of your items might not have any attachements @Mike_M. Perhaps you can change the code to account for this scenario, for example like so?

if ($input.item.binary) {
  $input.item.json.binaryItemsCount = Object.keys($input.item.binary).length;  
} else {
  $input.item.json.binaryItemsCount = 0;
}

return $input.item;

This would simply write 0 in the binaryItemsCount field if there is no binary data:

Workflow: