Skip to content

ClickHouse: Node.js (@clickhouse/client)

Loads the demo dataset over the ClickHouse HTTP interface and prints revenue per country.

# CLICKHOUSE_URL
https://clickhouse.internal:8443
https://warehouse.internal:8443
# CLICKHOUSE_USER / CLICKHOUSE_PASSWORD
ClickHouse user
MachWarehouse user
Terminal window
npm install
CLICKHOUSE_URL=https://warehouse.internal:8443 CLICKHOUSE_PASSWORD=... npm start

Library: @clickhouse/client 1.24.1 (Node.js 20+; tested target Node.js 26 LTS).

The program as it is kept and tested in the Mach Database Warehouse repository; highlighted lines read the connection setting.

index.mjs
// Load the demo events and print revenue per country with @clickhouse/client.
// Plain ClickHouse client code: nothing here knows about MachWarehouse.
import { readFileSync } from 'node:fs';
import { createClient } from '@clickhouse/client';
const dataset = new URL('../../dataset/', import.meta.url);
const client = createClient({
url: process.env.CLICKHOUSE_URL ?? 'https://localhost:8443',
username: process.env.CLICKHOUSE_USER ?? 'default',
password: process.env.CLICKHOUSE_PASSWORD,
database: process.env.CLICKHOUSE_DATABASE ?? 'default',
});
const [header, ...lines] = readFileSync(new URL('events.csv', dataset), 'utf8').trim().split('\n');
const names = header.split(',');
const values = lines.map((line) => Object.fromEntries(line.split(',').map((v, i) => [names[i], v])));
await client.command({ query: readFileSync(new URL('clickhouse.sql', dataset), 'utf8') });
await client.insert({ table: 'events', values, format: 'JSONEachRow' });
const rs = await client.query({
query: 'SELECT country, count() AS events, sum(revenue) AS revenue FROM events GROUP BY country ORDER BY revenue DESC',
format: 'JSONEachRow',
});
for (const row of await rs.json()) {
console.log(`${row.country}\t${row.events}\t${row.revenue}`);
}
await client.close();
package.json
{
"name": "machwarehouse-example-clickhouse-node",
"private": true,
"type": "module",
"scripts": { "start": "node index.mjs" },
"dependencies": { "@clickhouse/client": "1.24.1" },
"engines": { "node": ">=20" }
}