Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  77] [ 1]  / answers: 1 / hits: 17717  / 10 Years ago, wed, january 21, 2015, 12:00:00

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);



  • I hope its very simple and any one using sql.js can answer this.


More From » sqlite

 Answers
79

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:




  • test.js - file from above sample

  • sql.js - library file

  • Chinook_Sqlite.sqlite - Chinook test database



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>

[#68138] Monday, January 19, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;