TiDB Cloud Serverless Driver Node.js Tutorial
This tutorial describes how to use TiDB Cloud serverless driver in a local Node.js project.
Before you begin
To complete this step-by-step tutorial, you need the following:
- Node.js >= 18.0.0.
- npm or your preferred package manager.
- A TiDB Serverless cluster. If you don't have any, you can create a TiDB Serverless cluster.
Step 1. Create a local Node.js project
Create a project named
node-example
:mkdir node-example cd node-exampleInstall the TiDB Cloud serverless driver using npm or your preferred package manager.
The following command takes installation with npm as an example. Executing this command will create a
node_modules
directory and apackage.json
file in your project directory.npm install @tidbcloud/serverless
Step 2. Use the serverless driver
The serverless driver supports both CommonJS and ES modules. The following steps take the usage of the ES module as an example.
On the overview page of your TiDB Cloud Serverless cluster, click Connect in the upper-right corner, and then get the connection string for your database from the displayed dialog. The connection string looks like this:
mysql://[username]:[password]@[host]/[database]In the
package.json
file, specify the ES module by addingtype: "module"
.For example:
{ "type": "module", "dependencies": { "@tidbcloud/serverless": "^0.0.7", } }Create a file named
index.js
in your project directory and add the following code:import { connect } from '@tidbcloud/serverless' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) // replace with your TiDB Serverless cluster information console.log(await conn.execute("show tables"))Run your project with the following command:
node index.js
Compatability with earlier versions of Node.js
If you are using Node.js earlier than 18.0.0, which does not have a global fetch
function, you can take the following steps to get fetch
:
Install a package that provides
fetch
, such asundici
:npm install undiciPass the
fetch
function to theconnect
function:import { connect } from '@tidbcloud/serverless' import { fetch } from 'undici' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]',fetch})