पाठ 4 / 32

The Handler Contract

यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।

Write a FaaS handler, explain what the event and context objects carry, and test the handler locally with a fake event.

लेखक: · 15 साल से वेब डेवलपर

One function, called once per event

In FaaS you do not write a server that listens on a port. You export a handler function and the platform calls it once per event. On the AWS Lambda Node.js runtime the handler receives two arguments. The event is a JSON object whose shape depends on the trigger: an HTTP request, a batch of queue messages, a file-upload notification. The context carries metadata such as the request ID and a method that reports how much time is left before the timeout. Whatever an async handler returns becomes the result of the invocation, and a thrown error marks it as failed. Configuration tells the platform which file and export to call (for example index.handler), how much memory to allocate and what the timeout is. Because the platform owns the process, anything written to stdout or stderr is captured as logs automatically.

A minimal handler and a local smoke test

The handler is just an exported async function, so you can call it yourself with a hand-made event and context. That is the fastest feedback loop you will ever get.

// handler.mjs - a minimal AWS Lambda handler (Node.js runtime)
export const handler = async (event, context) => {
  const name = event.name ?? 'world';
  return {
    message: `Hello, ${name}!`,
    requestId: context.awsRequestId,
  };
};

// Local smoke test: call it like the runtime would.
const fakeContext = { awsRequestId: 'local-123' };
console.log(await handler({ name: 'Asha' }, fakeContext));

Output:

{ message: 'Hello, Asha!', requestId: 'local-123' }

Habits for clean handlers

Prefer async handlers that return a value or throw an error; callback-style handlers are legacy and newer runtimes may not support them. Never call process.exit() inside a handler, and do not start background work that you do not await: once the handler returns, the environment can be frozen mid-task.

त्वरित जाँच: In a Lambda Node.js handler `async (event, context) => {...}`, what is `event`?

  • A JSON payload whose shape depends on the trigger that invoked the function
  • An EventEmitter you must subscribe to with `.on()`
  • The function's configuration such as memory and timeout
  • A stream of log lines from previous invocations
Answer

A JSON payload whose shape depends on the trigger that invoked the function — The event is the input data from the trigger: an HTTP request, queue records, an S3 notification and so on. Configuration and logs are separate.