title | summary |
---|---|
TiDB Cloud Serverless Driver Node.js Tutorial |
Learn how to use TiDB Cloud serverless driver in a local Node.js project. |
This tutorial describes how to use TiDB Cloud serverless driver in a local Node.js project.
Note:
- This tutorial is applicable to TiDB Cloud Serverless clusters only.
- To learn how to use TiDB Cloud serverless driver with Cloudflare Workers, Vercel Edge Functions, and Netlify Edge Functions, check out our Insights into Automotive Sales and the sample repository.
To complete this step-by-step tutorial, you need the following:
- Node.js >= 18.0.0.
- npm or your preferred package manager.
- A TiDB Cloud Serverless cluster. If you don't have any, you can create a TiDB Cloud Serverless cluster.
-
Create a project named
node-example
:mkdir node-example cd node-example
-
Install 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
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 Cloud Serverless cluster information console.log(await conn.execute("show tables"))
-
Run your project with the following command:
node index.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 undici
-
Pass 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})