Reputation: 117
I am able to read the file when it is being uploaded using - input type="file", but I want to read the SQLite file from a hard coded path. The documentation for sql.js does provide a solution as given below, but i'm not able to get it working. Please help.
var fs = require('fs');
var SQL = require('sql.js');
var filebuffer = fs.readFileSync('test.sqlite');
// Load the db
var db = new SQL.Database(filebuffer);
Upvotes: 5
Views: 18786
Reputation: 4107
Probably the problem is in the location of sql.js
and test.sqlite
files. If you keep them in the same directory, write the name as './sql.js'
'./test.sqlite'
with dot and slash:
var fs = require('fs');
var SQL = require('./sql.js');
var data = fs.readFileSync('./Chinook_Sqlite.sqlite');
var sqldb = new SQL.Database(data);
I just run the code above, and it is works fine with Node.js (node test.js
). My directory has the following files:
UPDATE 2 People from SQL.js recommend to use this code (see SQL.js wiki) for recent versions of SQL.js:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
var db = new SQL.Database(uInt8Array);
var contents = db.exec("SELECT * FROM my_table");
// contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
xhr.send();
UPDATE 1 If you need to open SQLite files in the browser, you can use the code below (see the working example here):
<script src="sql.js"></script>
<script>
function loadBinaryFile(path,success) {
var xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var data = new Uint8Array(xhr.response);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
success(arr.join(""));
};
xhr.send();
};
loadBinaryFile('./Chinook_Sqlite.sqlite', function(data){
var sqldb = new SQL.Database(data);
// Database is ready
var res = db.exec("SELECT * FROM Genre");
});
</script>
Upvotes: 5