Performance: In-memory caching with node-cache
This concept affects server response time and reduces backend processing load, improving how fast pages or data are served to users.
import NodeCache from 'node-cache'; const cache = new NodeCache({ stdTTL: 60 }); app.get('/data', (req, res) => { const cachedData = cache.get('data'); if (cachedData) { return res.json(cachedData); } fetchFromDatabase().then(data => { cache.set('data', data); res.json(data); }); });
app.get('/data', async (req, res) => { const data = await fetchFromDatabase(); res.json(data); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching - fetch on every request | N/A (server-side) | N/A | N/A | [X] Bad |
| In-memory caching with node-cache | N/A (server-side) | N/A | N/A | [OK] Good |
node-cache in an Express app?node-cache?/data twice quickly?const express = require('express');
const NodeCache = require('node-cache');
const app = express();
const cache = new NodeCache();
app.get('/data', (req, res) => {
const cached = cache.get('myData');
if (cached) {
res.send('From cache: ' + cached);
} else {
const freshData = 'Hello World';
cache.set('myData', freshData, 10);
res.send('Fresh data: ' + freshData);
}
});
app.listen(3000);node-cache in Express:const NodeCache = require('node-cache');
const cache = NodeCache();
app.get('/item', (req, res) => {
const item = cache.get('itemKey');
if (!item) {
cache.set('itemKey', 'value');
res.send('Set new item');
} else {
res.send('Cached item: ' + item);
}
});node-cache. Which code snippet correctly sets the cache with expiration and retrieves it safely in Express?Pass the test and this pattern moves unknown