Performance: Separating routes into files
This affects the initial server startup time and memory usage, indirectly impacting response time and scalability.
const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); const productsRouter = require('./routes/products'); const ordersRouter = require('./routes/orders'); app.use('/users', usersRouter); app.use('/products', productsRouter); app.use('/orders', ordersRouter); app.listen(3000);
const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.send('Users list'); }); app.get('/products', (req, res) => { res.send('Products list'); }); app.get('/orders', (req, res) => { res.send('Orders list'); }); app.listen(3000);
| Pattern | File Size | Startup Time | Memory Usage | Verdict |
|---|---|---|---|---|
| Single large route file | Large | Longer | Higher | [X] Bad |
| Separated route files | Smaller per file | Shorter per file | Lower per file | [OK] Good |
users.js?express.Router() to create a new router instance.module.exports = router; to export it for use in other files.users.js:
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => {
res.send('User Profile');
});
module.exports = router;
And in app.js:
const express = require('express');
const app = express();
const usersRouter = require('./users');
app.use('/users', usersRouter);
app.listen(3000);
What will be the response when a client requests /users/profile?/users, so /profile inside router becomes /users/profile./profile sends 'User Profile' as response.products.js:
const express = require('express');
const router = express.Router();
router.get('/list', (req, res) => {
res.send('Product List');
});
// Missing module.exports here
And in app.js:
const express = require('express');
const app = express();
const productsRouter = require('./products');
app.use('/products', productsRouter);
app.listen(3000);
What error will occur when starting the app or accessing /products/list?module.exports is missing, require('./products') returns undefined.app.use causes an error when app tries to use it./api/users and /api/products into two files: users.js and products.js. Each file exports a router with routes starting at /. How should you mount these routers in app.js to correctly handle requests to /api/users/profile and /api/products/list?/, so mounting them at specific paths adds prefixes.usersRouter at /api/users and productsRouter at /api/products to match desired URLs.Pass the test and this pattern moves unknown