Async Routes
Part of the Express Basics section of Coddy's Node.js journey. Lesson 21 of 23.
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
EasyAn array in memory is lost every time the server restarts. Keep the recipes in a file instead: data/recipes.json, which already holds the four recipes.
- In
routes/recipes.js, importreadFileandwriteFilefromnode:fs/promises, and stop importingrecipesfrom../data.js. - Write one helper,
loadRecipes(), an async function that readsdata/recipes.jsonand returns the parsed list. The next lessons use it by that name. - Make every route in the file
async, and start each one by awaitingloadRecipes():/tags, the list, one recipe, the POST and the scale route. - In the POST route, after adding the new recipe to the list, write the whole list back to
data/recipes.jsonwithwriteFile, as JSON text. - The scale route still throws for a recipe without servings, now from inside an async function. Express 5 passes that error to your error handler as before, so it still responds with 500 and
{"error": "Something went wrong"}. Do not catch it in the route.
Try it: Press Run and send /api/recipes: the same four recipes, now read from the file. Pick POST and send {"title": "Gazpacho", "tags": ["vegan", "soup"]} to /api/recipes: status 201 and the recipe with "id": 5. Send /api/recipes/5: Gazpacho. Send /api/recipes/99: status 404. Then POST {"title": "Toast"}, which has no servings and becomes recipe 6, and send /api/recipes/6/scale?by=2: status 500 and {"error":"Something went wrong"}. If you see {} instead of your data, an await is missing.
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.
All lessons in Express Basics
Practice on your own: Express playground