mardi 1 décembre 2015

Storing json file to SQLite database using node

I am new to Javascript I am trying to store the json file into the database. But it's not working I am getting the below error:

$ node db.js
  module.js:339
  throw err;
  ^

Error: Cannot find module './commits.json'
at Function.Module._resolveFilename (module.js:
at Function.Module._load (module.js:287:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (c:\Documents and Setting e\db.js:8:10)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)

Below is the code, I have installed sqlite node module, I can manually insert the data using sql queries, I am struggling to figure out how to load the data from json file into the database. The json file is a log of git commits

var fs = require("fs");
var file = process.env.CLOUD_DIR + "test.db";
var exists = fs.existsSync(file);
var jsonfile = {
key: "myvalue"
};

myJson = require("./commits.json");

if(!exists) {
  console.log("Creating DB file.");
  fs.openSync(file, "w");
}

var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);

db.serialize(function() {
 if(!exists) {
   db.run("CREATE TABLE Stuff (thing TEXT)");
  }


 var jsonString = escape(JSON.stringify(myJson));

        db.transaction(function(tx){
            tx.executeSql('INSERT OR REPLACE INTO Stuff(md5, json, expires) VALUES ("'+hash+'", "'+jsonString+'","'+expireStamp+'")');
        },function(tx,error){
            console.log(JSON.stringify(tx.message));
            console.log(JSON.stringify(error));
        },function(){

            });
    db.close();

Aucun commentaire:

Enregistrer un commentaire