Getting Started with Connector/Node.js

spacer

MariaDB Connector/Node.js is a non-blocking MariaDB client.  It is 100% JavaScript and is compatible with Node.js 12+. This connector also includes enhanced features like batching and failover/load balancing via multi-node configuration.

There’s a lot to love in Connector/Node.js, which is why, in this article, I’ll be introducing you to MariaDB Connector/Node.js with simple examples that demonstrate create, read, update, and delete (CRUD) interactions with data stored in MariaDB. More specifically, I’m going to walk through the process of creating a new Node.js application.  With the help of a library called “Express” and Connector/Node.js, the new Node.js application provides API endpoints that can be used to read and write data to a MariaDB database.  But enough talk, let’s get started!

Requirements

Before jumping into the code, you’re going to need a few things on your machine:

  • Node.js (v.12+)
  • Curl (optional – used for testing the API endpoints)

Get started with MariaDB

Before you can create a new Java application that uses the MariaDB Connector/Node.js you will need access to a MariaDB Server instance. We recommend any one of these three methods:

1. Download MariaDB Server on your own hardware. See our Deployment Guide for step-by-step instructions.

OR

2. Create a new MariaDB Server containerized instance using the official MariaDB Docker image here.

OR

3. Use MariaDB SkySQL cloud database to deploy MariaDB Platform, which includes MariaDB Enterprise Server. See our documentation to launch a database service in minutes.

Prepare a MariaDB database

To test the MariaDB Connector/Node.js, the application you’re creating is going to need a schema to interact with.

Create Schema

Start by using a client of your choice to connect to your MariaDB instance.

Next, create a new database, named “todo”, for our application:

CREATE DATABASE todo;

Then, create a new table to store tasks:

CREATE TABLE todo.tasks (id int AUTO_INCREMENT PRIMARY KEY, description varchar(200), completed boolean DEFAULT false);

Add a new user

Optionally, you can create a new user that MariaDB Connector/Node.js can use to connect to and communicate with your MariaDB database instance.

CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'Password123!';
GRANT ALL PRIVILEGES ON todo.* TO 'app_user'@'localhost';

Going forward, “app_user” will be the user referenced in this walkthrough.

Create a Node.js project

Now that you’ve prepared your MariaDB database, you’re ready to put it to use within a new Node.js app.

Note: If you’d prefer to skip the walkthrough and jump directly into the code you can find it here.

To start, create a new directory, and then create a new Javascript file to be used as the main entry point for the Node server. For simplicity, I named the file server.js.

Then, within a terminal in that directory location, execute the following:

$ npm init

Note: If you’re unfamiliar with Node.js, note that the “npm” command is referring to Node Package Manager.

Once you’ve executed the above command, feel free to fill out all of the prompts, or you can just hit the enter key through all of the options. Either way, you’ll end up with a package.json file being generated next to server.js.

You now have a runnable, albeit not very interesting, Node.js application. But we’re just getting started!

Next you need to install a couple of Node.js packages, Express, Body-parser and MariaDB.

$ npm install --save express body-parser mariadb
  • Express is a lightweight web framework
  • Body-parser is used to parse incoming request bodies in a middleware before your handlers
  • MariaDB is Connector/Node.js, is used to connect to and communicate with MariaDB

Configuring Connector/Node.js

After you’ve created a new Node.js project, and have installed the necessary dependencies, it’s time to configure the freshly downloaded and installed MariaDB Node.js connector to be able to connect to and communicate with your MariaDB database.

Start by creating a new file called db.js, which will contain a new module, in the same directory that you previously created server.js (or whatever you might have named it).

Next, paste the following code into db.js:

// Use the MariaDB Node.js Connector
var mariadb = require('mariadb');
 
// Create a connection pool
var pool = 
  mariadb.createPool({
    host: “127.0.0.1”, 
    port: 3306,
    user: “app_user”, 
    password: “Password123!”,
    database: “todo”
  });
 
// Expose a method to establish connection with MariaDB SkySQL
module.exports = Object.freeze({
  pool: pool
});

The code above uses mariadb, the Node.js package for MariaDB Connector/Node.js, to first create a new connection pool using your database connection settings.

Note: In this walkthrough I have assumed you will be connecting to a local (127.0.0.1) instance of MariaDB. Please adjust your connection settings accordingly. Also, if you are wanting to connect to MariaDB SkySQL you can find more information on how to do so here.

The db module then exposes the (Connection) Pool object that can be used to execute queries on your MariaDB database!

Tip: You probably won’t want to just slap all that sensitive connection information directly into your connection module. Note that this has been done for simplicity. Instead, you may want to consider using something like dotenv to handle sensitive environmental data. You can find more information on how to do that for this sample here.

Expose API endpoints

Now that you’ve created a new Node.js application and configured it through the use of MariaDB Connector/Node.js to communicate with your MariaDB database, it’s time to add some code to test things out!

The following code, which should be copy and pasted into server.js, does a couple of things. First, and most importantly, it creates a new Express application that thereby allows you to expose HTTP request endpoints.

The following code also includes four functions, exposed as API endpoints, that perform the four basic CRUD (create, read, update, delete) operations on the database using MariaDB Connector/Node.js capabilities.

const express = require('express')
const db = require('./db')
const app = express()
const port = 8080
const bodyParser = require("body-parser");
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
// GET
app.get('/tasks', async (req, res) => {
    try {
        const result = await db.pool.query("select * from tasks");
        res.send(result);
    } catch (err) {
        throw err;
    }
});
 
// POST
app.post('/tasks', async (req, res) => {
    let task = req.body;
    try {
        const result = await db.pool.query("insert into tasks (description) values (?)", [task.description]);
        res.send(result);
    } catch (err) {
        throw err;
    }
});
 
app.put('/tasks', async (req, res) => {
    let task = req.body;
    try {
        const result = await db.pool.query("update tasks set description = ?, completed = ? where id = ?", [task.description, task.completed, task.id]);
        res.send(result);
    } catch (err) {
        throw err;
    } 
});
 
app.delete('/tasks', async (req, res) => {
    let id = req.query.id;
    try {
        const result = await db.pool.query("delete from tasks where id = ?", [id]);
        res.send(result);
    } catch (err) {
        throw err;
    } 
});
 
app.listen(port, () => console.log(`Listening on port ${port}`));

After you’ve copy and pasted the preceding code into your server.js file all that’s left to do is run the application. You can do so by opening a terminal at the root of your application and executing the following command.

$ npm start

Testing it out

Once the Node.js project has been started, you can test it by executing a request. This can be done through a variety of techniques.

For instance, consider executing the following curl command which can be used to add a new task, via a POST web request, to the tasks table within your MariaDB todo database:

$ curl --header "Content-Type: application/json" \
--request POST \
--data "\"Task 1\"" \
http://localhost:8080/tasks

Then you can confirm the addition by executing the following GET web request:

$ curl http://localhost:8080/people

Which should yield a payload similar to the following:

[{"id":1,"description":"Task 1",”completed”:false}]

To view this code in its entirety check out the source here.

(Tip: For more information on curl capabilities check out the official “How To Use” Guide.)

And if you’re thinking “it’d sure be nice to see an implementation with a user interface”, you’re in luck! You can find a fully fleshed out implementation of a TODO application using React.js and your choice of multiple API projects (R2DBC, JDBC, Node.js and Python) that integrate directly with MariaDB here.

Just the beginning

Hopefully this short walkthrough has helped you get started using MariaDB with Node.js. And, yeah, this was a very simple example, but it only gets more exciting from here! Stay tuned for more content on MariaDB Connector/Node.js!

Learn about developing modern applications with MariaDB on our new MariaDB Developer Hub.

Find the MariaDB Connector/Node.js enterprise documentation.