Connecting to SQLite Using Node.js
SQLite is a lightweight, serverless database engine that integrates easily with Node.js applications. On ruachost.com, you can connect to SQLite databases using the popular sqlite3 package.
Why Use Node.js with SQLite?
Section titled “Why Use Node.js with SQLite?”- Perfect for lightweight applications and prototyping.
- Stores data in a single portable
.dbfile. - Asynchronous I/O in Node.js makes queries fast and scalable.
- No external database server required.
Steps to Connect to SQLite Using Node.js
Section titled “Steps to Connect to SQLite Using Node.js”Step 1: Install Node.js and sqlite3
Section titled “Step 1: Install Node.js and sqlite3”-
Log in to your hosting account via SSH.
-
Ensure Node.js is installed.
-
Install the sqlite3 package:
Terminal window npm install sqlite3
Step 2: Write Connection Code
Section titled “Step 2: Write Connection Code”Example
Section titled “Example”// Import sqlite3import sqlite3 from 'sqlite3';
// Enable verbose mode for debuggingsqlite3.verbose();
// Connect to SQLite database file (creates if not exists)const db = new sqlite3.Database('example.db');
// Run queriesdb.serialize(() => { db.run("CREATE TABLE employees (firstname TEXT, lastname TEXT, title TEXT)"); db.run("INSERT INTO employees VALUES ('Kelly', 'Koe', 'Engineer')");
db.each("SELECT firstname, lastname FROM employees", (err, row) => { console.log(row.firstname + " " + row.lastname); });});
// Close connectiondb.close();Step 3: Handle Common Errors
Section titled “Step 3: Handle Common Errors”-
If you see:
SyntaxError: Cannot use import statement outside a module→ Create a
package.jsonfile in your project directory and add:{"type": "module"} -
This enables ES module syntax (
import) in Node.js..