D: n8nβs Code Node is a powerful tool that lets you write custom JavaScript/Python snippets to manipulate data, call APIs, or automate complex logic. But mastering it requires understanding key syntax and debugging techniques. Letβs break it down!
π§ 1. Essential Code Node Syntax
A. Accessing Input Data
Use $input
to access data from previous nodes. For example:
// Get data from the first input item
const data = $input.all()[0].json;
return { payload: data.name.toUpperCase() };
$input.all()
: Returns an array of all input items..json
: Accesses the JSON payload.
B. Returning Output
Always return an object with an array. Example:
return {
json: {
userId: 123,
status: "processed"
}
};
C. Using Libraries (JavaScript)
n8n supports built-in libraries like lodash
or moment
:
const _ = require('lodash');
return { json: _.capitalize("hello world") }; // Output: "Hello world"
D. Python Example
For Python, use the pd
(Pandas) or requests
library:
import requests
response = requests.get("https://api.example.com")
return [{ "data": response.json() }]
π 2. Debugging Like a Pro
A. console.log
is Your Friend
Use console.log()
to inspect variables:
const rawData = $input.all();
console.log("DEBUG:", rawData); // Check in the "Execution" tab!
B. Handle Errors Gracefully
Wrap code in try-catch
:
try {
const riskyData = $input.first().json.nonexistent.field;
} catch (error) {
console.log("Error caught:", error.message);
return { json: { error: "Safe fallback" } };
}
C. Validate Data Structure
Check if fields exist before accessing:
const user = $input.first().json;
if (user?.address?.city) { // Optional chaining
return { json: { city: user.address.city } };
}
D. Use the “Test Step” Button
π Click “Execute Node” to preview outputs without running the full workflow!
π‘ 3. Pro Tips
- Reuse Code: Save snippets in the “Code Snippets” section (Settings β Community Nodes).
- Environment Variables: Store API keys securely via
$env.VAR_NAME
. - Async/Await: For API calls, use promises:
const result = await fetch("https://api.example.com"); return { json: await result.json() };
π― Real-World Example
Scenario: Extract emails from a CSV, validate domains, and return clean data.
const items = $input.all();
const validEmails = items.map(item => {
const email = item.json.email;
if (email.includes("@company.com")) {
return { json: { validEmail: email } };
}
});
return validEmails.filter(Boolean);
π₯ Final Advice
- Start small: Test one function at a time.
- Document: Add comments for complex logic.
- Community Help: Join the n8n Slack for support!
Now go build something amazing! π
(Need more? Check n8nβs official docs!)