Reputation: 599
I would like to insert data into a SQlite3
db by pressing a button from an HTML
file.
In order to achieve this, I wrote a JS
script.
Unfortunately, when I press the button, I get this error message in my console.log:
script.js:5 Uncaught ReferenceError: require is not defined
Then, I tried to convert my JS file with browserify
but then I got this error:
Cannot read property '_handle' of undefined
Here my HTML and JS codes to reproduce the error:
HTML:
<head>
</head>
<body>
<div>
<label>SQLite3</label>
<button type="button">Connection</button>
</div>
<script src="script.js"></script>
</body>
JS:
function addData() {
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./data.db');
db.run('INSERT INTO info (result) VALUES (10)', function(err, row) {
if(err) {
console.log(err.message);
}
console.log("entry added to table");
});
}
addData();
Upvotes: 2
Views: 18398
Reputation: 64
You can't connect to sqlite database from client side, you have to connect from server side language. Perhaps you can use NodeJS as server side programming language.
follow these steps then it will work
STEP1 Download and install node js from https://nodejs.org/en/download/
STEP2 Install npm by following this instruction https://www.npmjs.com/get-npm
STEP3 Create Node js project by following this guides http://cassandrawilcox.me/setting-up-a-node-js-project-with-npm/
STEP4 Now you can install sqlite3 via npm.
After that you have to run server. If you are beginner then follow this https://www.w3schools.com/nodejs/
Upvotes: 0
Reputation: 943564
Browserify works around the problem that browsers don't have native support for the Node.js module system.
Browserify does not work around most other APIs that are provided by Node.js but not browsers. For example, Node.js has the fs
module which allows you to access the file system of the computer the code is running on. Browsers, on the other hand, don't allow access except in very particular and limited ways.
Since new sqlite3.Database('./data.db')
tries to read data from a file, it will not work in a browser.
Use a different API that is supported by browsers instead (such as IndexedDB or Web Storage.
Alternatively, if you want to share data between browsers, use Node.js to run a web server (e.g. with Express.js) and write a web service through which the database can be accessed.
Upvotes: 2