# The Code Node — AI Automation with n8n

Source: https://www.geekswithgeeks.com/en/n8n-ai-automation/data-code-node

> Write JavaScript in the Code node in both run modes and return items in the right shape.

## Two modes

The **Code** node runs JavaScript (or Python). In **Run Once for All Items** mode you read every item with `$input.all()` and must return an array of `{ json: {...} }`. In **Run Once for Each Item** mode you read `$input.item` and return one `{ json: {...} }`. Choose all-items mode for dedupe, sorting and aggregation, and each-item mode for simple per-record changes.

## Normalise and dedupe (all items)

I ran this logic in Node.js with sample items. Two input rows had the same email, so one is dropped, and the non-numeric amount `"abc"` becomes `NaN`, which JSON prints as `null`.

```javascript
const seen = new Set();
const out = [];
for (const item of $input.all()) {
  const email = item.json.email.trim().toLowerCase();
  if (seen.has(email)) continue;          // drop duplicates
  seen.add(email);
  out.push({ json: {
    name: item.json.name.trim(),
    email,
    amount: Number(item.json.amount),
  }});
}
return out;
```

Output:

```
[{"json":{"name":"Asha","email":"asha@example.com","amount":1200}},
 {"json":{"name":"Ravi","email":"ravi@example.com","amount":null}}]
```

## Validate before you continue

Filtering out rows whose amount is not a finite number keeps bad data out of the next system. On the same sample, 1 row is valid and 1 is rejected.

```javascript
const valid = out.filter(i => Number.isFinite(i.json.amount));
const invalid = out.length - valid.length;
return valid;   // log or route the invalid ones elsewhere
```

Output:

```
1 valid, 1 invalid
```

## Return the right shape

Returning plain objects instead of `{ json: ... }` items is the most common Code node error. When something looks wrong, check the node's output tab and read the error message; it names the expected shape.

**Quiz:** What must a Code node in "all items" mode return?

- [ ] A plain string
- [ ] Nothing
- [x] An array of objects with a json property
- [ ] A number

*Answer:* An array of objects with a json property. n8n expects items in the form { json: {...} }, returned as an array.
