【问题标题】:Storing json file to SQLite database using node使用节点将 json 文件存储到 SQLite 数据库
【发布时间】:2016-03-05 07:14:18
【问题描述】:

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

【问题讨论】:

    标签: json node.js sqlite


    【解决方案1】:

    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

    【讨论】:

    • 是的,已经解决了。但是如何将这些数据添加到数据库中?
    • 我会检查 redis 而不是 SQLlite。添加简单的 关系非常容易。 Sitepoint 教程:sitepoint.com/using-redis-node-js
    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2021-06-20
    • 2019-10-04
    • 2021-06-05
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多