Build an HTML Report#
Turn data into a standalone HTML file in your file system. Reports are plain files, so you can open them in the workbench, link to them, or serve them from an endpoint you control.
The Script#
// report.js
import fs from "fs";
const rows = [
{ name: "Ada", score: 92 },
{ name: "Grace", score: 97 },
{ name: "Linus", score: 88 },
];
const tableRows = rows
.map((row) => ` <tr><td>${row.name}</td><td>${row.score}</td></tr>`)
.join("\n");
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Score Report</title>
</head>
<body>
<h1>Score Report</h1>
<table>
<thead><tr><th>Name</th><th>Score</th></tr></thead>
<tbody>
${tableRows}
</tbody>
</table>
</body>
</html>`;
await fs.mkdir("/reports", { recursive: true });
await fs.writeTextFile("/reports/index.html", html);
console.log(`Report written with ${rows.length} rows`);
How It Works#
- The report is a template literal. Data is mapped to table rows, then the rows are joined into one string and inserted.
fs.writeTextFilewrites a string as UTF-8 bytes.
Escape any text that comes from an outside source before putting it in
the template, so a stray < cannot break the page.
Setup#
Create a job that points at report.js, run it, then open
/reports/index.html in the workbench.