A blog by Devendra Tewari
Node.js and Sqlite3 can be used as a foundation for apps that are cross-platform, browser-based (leverage HTML5), and network-intensive. In this post, I comment about some of the work required in building such a foundation.
Head over to the command prompt and run
npm install sqlite3
You can add the -g
option after npm
if you want to install to the global node_modules
folder.
I like to maintain a database creation script. The code below is a simple example of how I detect and execute the creation script.
var fs = require('fs');
var sqlite3 = require('sqlite3').verbose();
fs.exists('database', function (exists) {
db = new sqlite3.Database('database');
if (!exists) {
console.info('Creating database. This may take a while...');
fs.readFile('create.sql', 'utf8', function (err, data) {
if (err) throw err;
db.exec(data, function (err) {
if (err) throw err;
console.info('Done.');
});
});
}
});
Here’s how create.sql
may look like
CREATE TABLE customer (
id INT NOT NULL,
CONSTRAINT PK_customer PRIMARY KEY (id ASC)
);
CREATE TABLE sale (
id INT NOT NULL,
CONSTRAINT PK_sale PRIMARY KEY (id ASC)
);
It is rather convenient if you can package Node.js and its modules in a single installer. I discussed this in the post Adding lots of source files to a WiX installer script recently. I use npm
without the -g
option to download and install all modules in a node_modules folder. I place the single executable version of Node.js in the same folder. The installer just needs to package that folder, and you have a Windows-specific package of Node.js and your application’s module dependencies ready to install.