Introduction to Polka
Polka is a highly efficient and minimalistic routing framework for Node.js, designed to provide ultra-fast HTTP servers with minimal footprint. It is an ideal choice for developers seeking a lightweight alternative to Express without compromising on performance.
Setting Up Polka
To get started with Polka, you first need to install it via npm:
npm install polka
Basic Usage
Creating a basic server with Polka is straightforward:
const polka = require('polka'); const { json } = require('body-parser'); const { PORT=3000 } = process.env; const app = polka(); app.use(json()); app.get('/', (req, res) => { res.end('Hello, world!'); }); app.listen(PORT, err => { if (err) throw err; console.log(`> Running on localhost:${PORT}`); });
Using Middlewares
Polka supports middleware functions that can process requests before they reach the actual route handler. Here is an example:
app.use((req, res, next) => { console.log(`Incoming request to ${req.path}`); next(); });
Routing Parameters
Polka allows you to define route parameters easily:
app.get('/user/:id', (req, res) => { res.end(`User ID: ${req.params.id}`); });
Query String Parameters
Handle query string parameters like this:
app.get('/search', (req, res) => { const { query } = req; res.end(`Search Query: ${query.q}`); });
Handling Errors
Error handling in Polka can be done by passing an error to the next function:
app.get('/error', (req, res, next) => { next(new Error('Something went wrong!')); }); app.use((err, req, res, next) => { console.error(err.stack); res.statusCode = 500; res.end('Server Error'); });
Combining Routes
You can modularize your routing logic by combining routes from different files:
const userRoutes = polka() .get('/me', (req, res) => res.end('User Info')) .get('/:id', (req, res) => res.end(`User ID: ${req.params.id}`)); app.use('/user', userRoutes);
Example Application
Here is a more comprehensive example that combines several aspects of Polka:
const polka = require('polka'); const { json } = require('body-parser'); const app = polka(); app.use(json()); // Root Route app.get('/', (req, res) => { res.end('Welcome to Polka!'); }); // Middleware for Logging app.use((req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`); next(); }); // User Routes const userRoutes = polka() .get('/me', (req, res) => res.end('User Info')) .get('/:id', (req, res) => res.end(`User ID: ${req.params.id}`)); app.use('/user', userRoutes); // Error Handling app.use((err, req, res, next) => { console.error(err.stack); res.statusCode = 500; res.end('Internal Server Error'); }); const { PORT=3000 } = process.env; app.listen(PORT, err => { if (err) throw err; console.log(`> Running on localhost:${PORT}`); });
Polka is a versatile and high-performance framework that makes building fast and efficient web applications a breeze. With its minimalistic design and powerful features, it is a compelling choice for Node.js developers.
Hash: 837f421cd685e050af8c5f8ac3c179944228c030b282fb9654e4c81c64da77fd