Section 5: Building a CRUD App - The Food Ingredients Database
Our API works, but your users (and your boss) want buttons. Let's add a single-page front end, then keep the app running properly with PM2.
Express is already serving the public folder (express.static in server.js), so this file appears at http://myibmi:3000/.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ingredients - Node.js on IBM i</title>
<style>
body { font-family: system-ui, sans-serif; margin: 2rem; background: #f7f7f2; }
table { border-collapse: collapse; width: 100%; background: #fff; }
th, td { border: 1px solid #ccc; padding: .4rem .6rem; text-align: left; }
th { background: #2e7d32; color: #fff; }
form { margin: 1rem 0; display: flex; gap: .5rem; flex-wrap: wrap; }
input { padding: .3rem; }
#msg { color: #b00020; min-height: 1.2em; }
</style>
</head>
<body>
<h1>
<form id="form">
<input type="hidden" id="id">
<input id="name" placeholder="Name" required maxlength="100">
<input id="category" placeholder="Category" maxlength="50">
<input id="unit" placeholder="Unit (g, ml, each)" maxlength="20">
<input id="quantity" type="number" step="0.01" min="0" placeholder="Quantity">
<input id="calories" type="number" step="1" min="0" placeholder="Calories /100">
<button type="submit">Save</button>
<button type="button" id="clear">Clear</button>
</form>
<div id="msg"></div>
<table>
<thead>
<tr><th>ID</th><th>Name</th><th>Category</th><th>Unit</th><th>Qty</th><th>Calories</th><th></th></tr>
</thead>
<tbody id="rows"></tbody>
</table>
<script>
const API = '/api/ingredients';
const $ = id => document.getElementById(id);
async function api(url, options = {}) {
const res = await fetch(url, { headers: { 'Content-Type': 'application/json' }, ...options });
if (res.status === 204) return null;
const data = await res.json();
if (!res.ok) throw new Error(data.error || (data.errors || []).join(', '));
return data;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));
}
async function load() {
const items = await api(API);
$('rows').innerHTML = items.map(i => `
<tr>
<td>${i.id}</td><td>${escapeHtml(i.name)}</td><td>${escapeHtml(i.category)}</td>
<td>${escapeHtml(i.unit)}</td><td>${i.quantity}</td><td>${i.calories}</td>
<td>
<button onclick='edit(${JSON.stringify(i).replace(/'/g, "'")})'>Edit</button>
<button onclick="removeItem(${i.id})">Delete</button>
</td>
</tr>`).join('');
}
function edit(i) {
for (const f of ['id', 'name', 'category', 'unit', 'quantity', 'calories']) $(f).value = i[f];
}
async function removeItem(id) {
if (!confirm('Delete ingredient ' + id + '?')) return;
try { await api(`${API}/${id}`, { method: 'DELETE' }); $('msg').textContent = ''; load(); }
catch (e) { $('msg').textContent = e.message; }
}
$('form').addEventListener('submit', async e => {
e.preventDefault();
const body = {
name: $('name').value,
category: $('category').value || 'Other',
unit: $('unit').value || 'g',
quantity: Number($('quantity').value || 0),
calories: Number($('calories').value || 0),
};
const id = $('id').value;
try {
await api(id ? `${API}/${id}` : API, { method: id ? 'PUT' : 'POST', body: JSON.stringify(body) });
$('form').reset(); $('id').value = ''; $('msg').textContent = '';
load();
} catch (err) {
$('msg').textContent = err.message;
}
});
$('clear').addEventListener('click', () => { $('form').reset(); $('id').value = ''; });
load().catch(e => $('msg').textContent = e.message);
</script>
</body>
</html>
Then:
pm2 status
pm2 logs ingredients-app
pm2 restart ingredients-app
pm2 stop ingredients-app
Starting it when the system IPLs
PM2's startup command targets Linux init systems, which IBM i doesn't have. The IBM i way is a batch job. Submit it from your startup program (or add an autostart job entry):
SBMJOB CMD(QSH CMD('cd /home/NICK/ingredients-app && /QOpenSys/pkgs/bin/pm2 start ecosystem.config.js')) JOB(INGREDAPP) JOBQ(QSYSNOMAX) USER(NICK)(Alternatively, look at IBM's Service Commander - yum install service-commander - which is designed exactly for starting and stopping open source services on IBM i.)
Where to go next
- Add authentication (e.g.
express-session, or JWT via a well-known npm package). - Put HTTPS in front - either Node's
httpsmodule or the IBM HTTP Server as a reverse proxy. - Call an RPG program from a route with
itoolkit(Section 4) - e.g. price lookups. - Write tests with Node's built-in
node:testrunner.
And that's it! You've installed Node.js on IBM i, learned why it's worth your time, built web services with Express, and created a full CRUD app on a Db2 for i table. Not bad for a bunch of old green-screen programmers, eh?
Now go and make something tasty.
