Connect with Node.js

Use the SingleStore Node.js driver (singlestore-nodejs dependency) to connect Node.js applications to SingleStore databases, whether using an ORM or straight SQL. The singlestore-nodejs dependency supports configuring the connection behavior, prepared statements, compression, SSL, and more.

Refer to SingleStore-Nodejs for more information related to the driver's implementation, supported features, and usage patterns. Refer to the SingleStore Node.js Driver GitHub repository for its source code and related information.

To connect from Node.js to SingleStore using SSL, refer to Connect with Node.js using SSL.

Install the SingleStore Node.js Driver

Install the singlestore-nodejs dependency to use the SingleStore Node.js driver:

npm install --save singlestore-nodejs

To add TypeScript type definitions, run the following command:

npm install --save-dev @types/node

Configure the Connection to SingleStore

The driver supports both Promise-based and callback-based programming models for handling asynchronous operations. Use the following connection configuration parameters with the respective model to configure the connection to SingleStore:

  • hostname: IP address or hostname of the SingleStore cluster.

  • port: Port of the SingleStore cluster. The default is 3306.

  • username: Username of the SingleStore database user.

  • password: Password for the SingleStore database user.

  • database: (Optional) Name of the SingleStore database to connect with.

Using Promises

import singlestore from "singlestore-nodejs/promise";
const connection = await singlestore.createConnection({
host: "<hostname>",
port: 3306,
user: "<username>",
password: "<password>",
database: "<database_name>",
});

Using Callbacks

const singlestore = require("singlestore-nodejs");
const connection = singlestore.createConnection({
host: "<hostname>",
port: 3306,
user: "<username>",
password: "<password>",
database: "<database>",
});
connection.connect((err) => {
if (err) {
console.error("Connection error:", err);
return;
}
console.log("Connected to SingleStore.");

Example

The following example connects to a SingleStore database and performs basic CRUD operations.

  1. Create a Node.js project.

    mkdir nodeJs
    cd nodeJs
    npm init -y
  2. Install the singlestore-nodejs dependency.

    npm install singlestore-nodejs
  3. Enable ES modules. Add "type": "module" to package.json. For example:

    {
    "name": "nodejs",
    "version": "1.0.0",
    "description": "",
    "type": "module",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
    "singlestore-nodejs": "^1.0.1"
    }
    }
  4. Add the following code to the index.js file. Update the connection configuration of your SingleStore database in the code.

    import singlestore from "singlestore-nodejs/promise";
    // == Update the SingleStore database connection config) ==
    const config = {
    host: "svchost-xxxx",
    user: "s2user",
    password: "p455w1kd",
    database: "dbTest",
    port: 3306,
    };
    async function main() {
    let conn;
    try {
    // 1. CONNECT
    conn = await singlestore.createConnection(config);
    console.log("Connected to SingleStore.");
    // 2. CREATE TABLE
    await conn.execute(`
    CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
    )`);
    console.log("Table ready.");
    // 3. INSERT
    const [insertResult] = await conn.execute(
    "INSERT INTO users (name) VALUES (?)",
    ["Green"]);
    console.log("Inserted ID:", insertResult.insertId);
    const userId = insertResult.insertId;
    // 4. READ
    const [rows] = await conn.execute(
    "SELECT * FROM users WHERE id = ?",
    [userId]);
    console.log("Read:", rows);
    // 5. UPDATE
    await conn.execute(
    "UPDATE users SET name = ? WHERE id = ?",
    ["Mink", userId]);
    console.log("Updated user.");
    // 6. VERIFY UPDATE
    const [updatedRows] = await conn.execute(
    "SELECT * FROM users WHERE id = ?",
    [userId]);
    console.log("After update:", updatedRows);
    // 7. DELETE
    await conn.execute("DELETE FROM users WHERE id = ?", [userId]);
    console.log("Deleted user.");
    } catch (err) {
    console.error("Error:", err);
    } finally {
    if (conn) {
    await conn.end();
    console.log("Connection closed."); }
    }
    }
    main();
  5. Run the application.

    node index.js
    Connected to SingleStore.
    Table ready.
    Inserted ID: 1
    Read: [ { id: 1, name: 'Green' } ]
    Updated user.
    After update: [ { id: 1, name: 'Mink' } ]
    Deleted user.
    Connection closed.

Additional Examples

References

In this section

Last modified:

Was this article helpful?