금. 8μ›” 15th, 2025

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

  1. Reuse Code: Save snippets in the “Code Snippets” section (Settings β†’ Community Nodes).
  2. Environment Variables: Store API keys securely via $env.VAR_NAME.
  3. 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!)

λ‹΅κΈ€ 남기기

이메일 μ£Όμ†ŒλŠ” κ³΅κ°œλ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. ν•„μˆ˜ ν•„λ“œλŠ” *둜 ν‘œμ‹œλ©λ‹ˆλ‹€