Node-DuckDB API > Connection > execute
Asynchronously executes the query and returns a Readable stream that wraps the result set.
Signature:
execute<T>(command: string, options?: IExecuteOptions): Promise<Readable>;
Parameter | Type | Description |
---|---|---|
command | string | SQL command to execute |
options | IExecuteOptions | optional options object of type IExecuteOptions |
Returns:
Promise<Readable>
Streaming results of a DuckDB query into a CSV file:
import { Connection, DuckDB, RowResultFormat } from "node-duckdb";
import { createWriteStream } from "fs";
import { Transform } from "stream";
class ArrayToCsvTransform extends Transform {
constructor() {
super({ objectMode: true });
}
_transform(chunk: any[], _encoding: string, callback: any) {
this.push(chunk.join(",") + "\n");
callback();
}
}
async function outputToFileAsCsv() {
const db = new DuckDB();
const connection = new Connection(db);
await connection.execute("CREATE TABLE people(id INTEGER, name VARCHAR);");
await connection.execute("INSERT INTO people VALUES (1, 'Mark'), (2, 'Hannes'), (3, 'Bob');");
const resultStream = await connection.execute("SELECT * FROM people;", { rowResultFormat: RowResultFormat.Array });
const transformToCsvStream = new ArrayToCsvTransform();
const writeStream = createWriteStream("my-people-output");
resultStream.pipe(transformToCsvStream).pipe(writeStream);
}
outputToFileAsCsv();