Use previous node value in JavaScript

Describe the problem/error/question

I would like to use the output value from a previous node in the Code node within JavaScript. I tried in the first line to add it but seems not to work. I thought just drag and drop would work but nothing happens…

Please share your workflow

const connectedStartTime = new Date({{$json.body[0].payload.object.connected_start_time}});
const callEndTime = new Date(“2024-01-17T08:29:02.000Z”);

const diffInMilliseconds = callEndTime - connectedStartTime;
const diffInMinutes = diffInMilliseconds / (1000 * 60);

return { json: { minutes_between: diffInMinutes } };

{
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "49181f157206142a160f7a5af8b9cc62690b903dcda183bc128b91dc11ce6d9b"
  },
  "nodes": [
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const connectedStartTime = new Date({{$json.body[0].payload.object.connected_start_time}});\nconst callEndTime = new Date(\"2024-01-17T08:29:02.000Z\");\n\nconst diffInMilliseconds = callEndTime - connectedStartTime;\nconst diffInMinutes = diffInMilliseconds / (1000 * 60);\nconsole.log(`Difference in minutes: ${diffInMinutes}`);\n"
      },
      "id": "1505d285-c3f3-46f1-8941-d26ebb16b7cc",
      "name": "Code",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1940,
        240
      ]
    }
  ],
  "connections": {},
  "pinData": {}
}

Any suggestion/idea?

With a set module before it worked

// Retrieve values from the Set node
const startDate = $json.startDate;
const endDate = $json.endDate;

// Check if startDate and endDate are defined
if (startDate === undefined || endDate === undefined) {
return { json: { formattedTime: null } };
}

// Calculate the time difference in milliseconds
const diffInMilliseconds = new Date(endDate) - new Date(startDate);

// Calculate minutes and seconds
const minutes = Math.floor(diffInMilliseconds / (1000 * 60));
const seconds = Math.floor((diffInMilliseconds % (1000 * 60)) / 1000);

// Format the time as MM:SS
const formattedTime = ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')};

return {
json: {
formattedTime: formattedTime
}
};

Is there a possibility to access them without set before?

Hi @Sebastian1, there is :slight_smile:

In your Code node you’re using a snippet like const connectedStartTime = new Date({{$json.body[0].payload.object.connected_start_time}});

The curly braces {{ and }} would mark the start and end of a JavaScript expression in n8n, when using the Code node you are already writing JavaScript. So you can simply omit these curly braces to use all the expressions.