पाठ 3 / 32

आपका पहला सर्वर

Async handlers के साथ कुछ lines में एक route वाला चलता Fastify server बनाएँ।

हैलो, वर्ल्ड!

एक instance बनाएँ, एक route परिभाषित करें, और सर्वर शुरू करें। async प्रकृति पर ध्यान दें—Fastify async-first है।

import Fastify from 'fastify';

const fastify = Fastify();

fastify.get('/', async (request, reply) => {
  return { message: 'Hello, World!' };
});

await fastify.listen({ port: 3000 });
console.log('Server running on http://localhost:3000');

Output:

Server running on http://localhost:3000

Fastify instance

Fastify() सर्वर instance बनाता है। fastify.get(route, handler) एक GET route रजिस्टर करता है। await fastify.listen() graceful shutdown समर्थन के साथ HTTP सर्वर शुरू करता है।

त्वरित जाँच

त्वरित जाँच: Fastify async/await का उपयोग क्यों करता है?

  • यह Node.js द्वारा आवश्यक है
  • Callbacks का उपयोग हटा दिया गया है
  • I/O operations को साफ-साफ handle करने और प्रदर्शन बनाए रखने के लिए
  • यह server को single-use बनाता है
Answer

I/O operations को साफ-साफ handle करने और प्रदर्शन बनाए रखने के लिए — Fastify async/await पर बना है ताकि asynchronous operations को efficiently handle कर सके और non-blocking event loop को साफ रखे।