The Node.js ecosystem

If I had a pound for every time an IBM i customer asked for "that report, but in a spreadsheet," I could retire to a very nice tea shop.

This is a job RPG shops know backwards: read some rows, write a file, leave it somewhere the user can pick it up. In Node.js the same idea takes about a page of code, and the file you write is a real .xlsx - the sort Excel, LibreOffice and Google Sheets all open without complaining.

We'll use ExcelJS (exceljs on npm) and the FOODLIB.INGREDIENTS table from Section 5, so you can run this on the same data as the CRUD app. The same pattern works for any SQL you like - sales, orders, a stock take, the works.

Set up a small project

A report is a good candidate for its own folder. It doesn't need Express, just the database driver and the spreadsheet library.

bash

mkdir -p ~/ingredients-report && cd ~/ingredients-report
npm init -y
npm install exceljs odbc dotenv

Create a `.env` file, the same shape as Lesson 5.2, and lock it down:

# .env
DB_USER=NICK
DB_PASS=changeme
DB_DSN=*LOCAL
chmod 600 .env

A useful aside: the ODBC connection string

We first connected to Db2 in Lesson 3.3. Here are the keywords I reach for most often on IBM i, because they save a lot of head-scratching:

DB2 for i ODBC Connection String

IBM documents the full list under [connection string keywords]. Our ingredients table was created with SQL naming (FOODLIB.INGREDIENTS), so this lesson leaves NAM at the default and uses the qualified name in the query.

The report program

Create ingredients-report.js:

javascript

// ingredients-report.js
// Read FOODLIB.INGREDIENTS and write ingredients.xlsx in the current directory.
require('dotenv').config();

const odbc = require('odbc');
const ExcelJS = require('exceljs');

async function main() {
const conn = await odbc.connect(
`DSN=${process.env.DB_DSN};UID=${process.env.DB_USER};PWD=${process.env.DB_PASS};CMT=0;`
);

const rows = await conn.query(
'SELECT ID, NAME, CATEGORY, UNIT, QUANTITY, CALORIES ' +
'FROM FOODLIB.INGREDIENTS ' +
'ORDER BY ID'
);

const workbook = new ExcelJS.Workbook();
workbook.creator = 'Node.js on IBM i';
workbook.created = new Date();

const sheet = workbook.addWorksheet('Ingredients');

// Column "key" values must match the Db2 column names in the result set.
// Unquoted IBM i column names come back in uppercase.
sheet.columns = [
{ header: 'Id', key: 'ID', width: 8, style: { numFmt: '0' } },
{ header: 'Name', key: 'NAME', width: 28 },
{ header: 'Category', key: 'CATEGORY', width: 14 },
{ header: 'Unit', key: 'UNIT', width: 8 },
{ header: 'Quantity', key: 'QUANTITY', width: 12, style: { numFmt: '#,##0.00' } },
{ header: 'Calories / 100', key: 'CALORIES', width: 16, style: { numFmt: '#,##0' } },
];

sheet.getRow(1).font = { name: 'Calibri', size: 11, bold: true };

for (const row of rows) {
sheet.addRow({
ID: Number(row.ID),
NAME: row.NAME,
CATEGORY: row.CATEGORY,
UNIT: row.UNIT,
QUANTITY: Number(row.QUANTITY),
CALORIES: Number(row.CALORIES),
});
}

// writeFile returns a Promise - always await it, or the job can end
// before the file has been flushed to the IFS.
const outFile = 'ingredients.xlsx';
await workbook.xlsx.writeFile(outFile);
await conn.close();

console.log(`Wrote ${rows.length} rows to ${outFile}`);
}

main().catch((err) => {
console.error(err);
process.exit(1);
});

A few things worth lingering on:

  • sheet.columns defines the heading, the width, and a key that ExcelJS uses to pick the matching field off each row. The key on each column tells ExcelJS which property to read. I map the fields explicitly and run Number(...) on the numeric ones: ODBC sometimes hands decimals back as strings, and an explicit map also avoids any surprise if the driver gives you an array-like row
  • numFmt is Excel's own format string. #,##0.00 gives you thousands separators and two decimals; $#,##0.00_);[Red]($#,##0.00) is the classic "red negatives with a currency symbol" if you're writing money (we used it for order totals when I first wrote a report like this)
  • await workbook.xlsx.writeFile(...) is important. The method is asynchronous. If you forget to await it, your script can close the connection, print "done," and end the process while the file is still being written. You then get a truncated or zero-byte spreadsheet, and a very unfair argument with Excel

Run it

bash

cd ~/ingredients-report
node ingredients-report.js

You should see something like:

Wrote 5 rows to ingredients.xlsx

The file lands in the current directory, which is the IFS (/home/NICK/ingredients-report/ingredients.xlsx if that's where you are). Pull it down with VS Code, ACS's IFS window, or scp, and open it. You get a proper workbook: bold headings, column widths, formatted numbers, one row per ingredient.

To write somewhere else, pass a full IFS path:

javascript

await workbook.xlsx.writeFile('/home/NICK/reports/ingredients.xlsx');

Make sure the folder exists and the user running the job can write to it.

Running it as a batch job

Interactive SSH is fine for testing. For a real morning report, submit it so it doesn't depend on your terminal staying open. Batch jobs do not read your .profile, so don't rely on node being on the PATH - call nodejs24 by its full path

SBMJOB CMD(QSH CMD('cd /home/NICK/ingredients-report && /QOpenSys/pkgs/lib/nodejs24/bin/node ingredients-report.js')) JOB(INGRDRPT) JOBQ(QSYSNOMAX)

(Use your own home directory, obviously.) You can schedule that from a job scheduler entry, or from your startup program if it should run after an IPL.

In the next lesson we'll email that spreadsheet to whoever asked for it, so nobody has to go hunting in the IFS with their morning tea.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>