Async Routes
Part of the Express Basics section of Coddy's Node.js journey. Lesson 18 of 20.
An array is gone when the server restarts. A file keeps the data.
import { readFile } from 'node:fs/promises';
app.get('/api/forecast', async (req, res) => {
const text = await readFile('data/forecast.json', 'utf8');
res.json(JSON.parse(text));
});A route can be an async function that waits with await, here for readFile from node:fs/promises. Express 5 watches the promise the route returns: if it rejects, because the file is missing or its JSON is broken, the error goes to your error handler, like a throw.
Without await you hold a promise instead of the data, and res.json(promise) sends {}. The new data/recipes.json holds the four recipes.
Challenge
Easy- Every route in
routes/recipes.jsreads the recipes fromdata/recipes.jsonon each request. POSTsaves the new list back withwriteFile.
Post a recipe, then send GET /api/recipes, GET /api/recipes/5 and GET /api/recipes/99.
Try it yourself
import express from 'express';
import { recipes } from '../data.js';
const router = express.Router();
// Every tag, once, in alphabetical order.
router.get('/tags', (req, res) => {
const tags = new Set(recipes.flatMap((recipe) => recipe.tags));
res.json([...tags].sort());
});
router.get('/', (req, res) => {
res.json(recipes);
});
router.get('/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
router.post('/', (req, res) => {
const { title, tags } = req.body;
if (!title) {
res.status(400).json({ error: 'A recipe needs a title' });
return;
}
const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
recipes.push(recipe);
res.status(201).json(recipe);
});
router.get('/:id/scale', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
const by = Number(req.query.by);
if (!Number.isFinite(by) || by <= 0) {
res.status(400).json({ error: 'Scale by a positive number' });
return;
}
if (!recipe.servings) {
throw new Error(`Recipe ${recipe.id} has no servings`);
}
res.json({ title: recipe.title, servings: recipe.servings * by });
});
export default router;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.