Skip to content

Run a headless Pivot report in Node.js and export the results ​

Use createPivotController from @revolist/pivot/headless to run a Pivot report directly in Node.js. Pass in a report definition and the source records, call refresh(), then read the result or export it to CSV, XLSX or HTML.

The example groups four orders by region and writes the report files to disk. The same controller works in a background job or behind a custom interface. Your application supplies the data and handles permissions and delivery.

Pivot product · Headless feature guide · Controller reference and live example · Complete executable source

Run a complete reporting job ​

From examples/pivot-workflows in the documentation repository:

bash
npm ci
npm run headless

Use Node 24.13 or later. The example runs with the pinned trial packages and needs only the supplied sales records.

The program creates four files in its local output directory:

FileContents
sales.csvThe committed report in CSV form
sales.xlsxThe committed report as an XLSX workbook
sales.htmlAn HTML table suitable for a host print workflow
report.jsonThe portable report definition for later restoration

The example's public trial aliases keep trial restrictions enabled. For licensed deployment, follow the installation instructions and replace the aliases. Access to a headless import does not change the product's commercial license.

Define a report independently of the interface ​

The fixture has one North order worth 10 and three South orders worth 20 each:

js
const source = [
  { region: 'North', sales: 10 },
  { region: 'South', sales: 20 },
  { region: 'South', sales: 20 },
  { region: 'South', sales: 20 },
];

The report uses a stable field ID for each input and a separate ID for each measure:

js
const report = {
  kind: 'revogrid:pivot.report',
  version: 1,
  aggregationSemantics: 'local',
  fields: [
    { id: 'region', sourceProp: 'region' },
    { id: 'sales', sourceProp: 'sales' },
  ],
  rows: ['region'],
  columns: [],
  filters: [],
  measures: [
    { id: 'sales-total', fieldId: 'sales', aggregator: 'sum', label: 'Sales' },
    { id: 'order-average', fieldId: 'sales', aggregator: 'avg', label: 'Average order' },
  ],
  totals: { grandTotal: true },
};

version: 1 refers to the portable report schema. The report stores the layout and measure definitions, and the caller supplies the source records.

The execution pin records that this report uses local aggregation. Restoring a saved layout should not silently move it onto a different backend with different count, null or precision semantics.

Execute first, then inspect the committed model ​

Controller construction starts idle by default. Explicitly refresh and handle the operation's outcome:

js
import { createPivotController } from '@revolist/pivot/headless';

const controller = createPivotController({ report, source });
try {
  const outcome = await controller.refresh();
  if (outcome.status !== 'committed') {
    throw new Error(JSON.stringify(outcome));
  }

  const snapshot = controller.getSnapshot();
  const { columns, source: rows, pinnedBottomSource } = snapshot.view.model;
  process.stdout.write(JSON.stringify({ columns, rows, pinnedBottomSource }, null, 2));
} finally {
  controller.dispose();
}

The body contains North and South. The grand total belongs to pinnedBottomSource; it is not an ordinary input row.

OutputSalesAverage order
North1010
South6020
Grand total7017.5

All four orders count toward the grand-total average, so the result is 70 / 4 = 17.5. Averaging the two regional averages would give 15 because it would give North and South equal weight. The example checks for 17.5 before writing the exports.

The fixture intentionally contains finite numbers. It does not rely on implicit conversion of user-entered strings or missing values. If an application accepts those inputs, validate them or define an explicit numeric policy before aggregation.

Use the generated columns to read values ​

Pivot creates output properties for its analytical coordinates. Avoid assuming that a source field named sales remains row.sales in the result.

The example flattens the generated column tree, resolves the expected labeled output, and reads row[column.prop]. Its labels are unique within this small report. A general custom interface should use the supported model metadata and stable report identities rather than making display labels its persistent key.

Likewise, consume snapshot.view.model as a committed result. Do not mix its columns with a row array from an earlier execution. The controller reference explains committed and pending state for interfaces that allow users to change reports while work is running.

Export through the same controller ​

After the successful refresh, the export methods use the committed view:

js
import { mkdir, writeFile } from 'node:fs/promises';

await mkdir('output', { recursive: true });
await writeFile('output/sales.csv', controller.exportCsv());
await writeFile('output/sales.xlsx', controller.exportXlsx());
await writeFile('output/sales.html', controller.buildPrintTable());
await writeFile('output/report.json', controller.exportReportJson());

CSV is returned as text; XLSX is returned as a byte array. File creation is ordinary Node application code. The controller does not choose a filesystem path or upload files on your behalf.

The local export contains both regions and the grand total. For a remote, paged report, the loaded window may represent only part of the result. Calling the ordinary visible export methods is not proof of complete server export. Use the separate complete server report contract when all filtered groups must be included.

Handle a failed report refresh ​

A controller may retain the prior committed view when a later operation fails. That is useful for an interactive UI, but a background job must not interpret the retained data as a successful replacement.

The runnable example configures explicit bounds:

js
const controller = createPivotController({
  report,
  source,
  resourceLimits: {
    maxSourceSlots: 100,
    maxExportDataCells: 1000,
    maxExportUtf8Bytes: 100_000,
    maxWorkbookXmlBytes: 200_000,
  },
});

It then attempts to replace the source with 101 records. The check verifies that the operation is refused, the committed revision and view stay unchanged, and replacing the source with the original four records succeeds again.

For a scheduled export, inspect every operation outcome before writing the new file or marking the job complete. Also catch synchronous validation and export exceptions; not every refusal arrives as a failed asynchronous outcome. These limits bound admitted work and output. They are not a substitute for a job timeout or a process-level memory limit.

Restore a saved report definition ​

exportReportJson() serializes the report definition. The public parser restores that definition:

js
import { parsePivotReport } from '@revolist/pivot/headless';

const restored = parsePivotReport(savedJson);
const next = createPivotController({ report: restored, source: authorizedRows });

The application still resolves the authorized source and any runtime bindings. A saved report is not permission to access a field, tenant or database. Store your application's dataset version or job watermark separately when the output needs an audit trail.

If a report comes from an untrusted user, apply your field and operation policy as well as parser validation. A structurally valid report can still request work that your product should not expose.

Where headless Pivot fits ​

NeedAppropriate integration
A local Node job that aggregates already authorized recordsHeadless controller with local source
A custom analytical interface without the grid elementHeadless controller with application rendering
An interactive RevoGrid Pivot already on a pageExisting Pivot plugin and its authoring controller
A warehouse report over data that should remain in the databaseServer adapter and backend aggregation

Headless means the workflow does not require the grid element. It does not promise a smaller dependency footprint: the headless subpath shares runtime modules with the package. Local execution still needs the source data in the Node process; it is not automatically a streaming aggregation engine or SQL pushdown layer.

This example uses a local V1 report. See the calculation tutorial for the V2 trial compatibility issue.

For weighted measures and sequence calculations, continue with the numerical calculation walkthrough. For database-owned calculations, use the working SQL Pivot endpoint.