使用节点将json文件存储到SQLite数据库

时间:2015-12-01 11:21:13

标签: json node.js sqlite

我是Javascript的新手我试图将json文件存储到数据库中。 但它无法正常工作我收到以下错误:

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

下面是代码,我已经安装了sqlite节点模块,我可以使用sql查询手动插入数据,我正在努力弄清楚如何将数据从json文件加载到数据库中。 json文件是git提交的日志

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

1 个答案:

答案 0 :(得分:0)

myJson = require("./commits.json");导致您的错误。您没有正确读取文件,而是尝试将其作为节点模块包含。

你想做更像

的事情
// async read
fs.readFile('commits.json', function (err, data) {
   if (err) {
       return console.error(err);
   }
   console.log("File content: " + data.toString());
   // now save to db
});

详细了解File System

相关问题