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?
-
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
Step 1: Install Node.js and sqlite3
-
Log in to your hosting account via SSH.
-
Ensure Node.js is installed.
-
Install the sqlite3 package:
Bash npm install sqlite3
Step 2: Write Connection Code
Example:
// Import sqlite3
import sqlite3 from 'sqlite3';
// Enable verbose mode for debugging
sqlite3.verbose();
// Connect to SQLite database file (creates if not exists)
const db = new sqlite3.Database('example.db');
// Run queries
db.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 connection
db.close();
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..
Important Notes
|