NodeJS .forEach()中的MySQL查询似乎只执行/执行一次

时间:2017-02-08 17:27:24

标签: mysql node.js

我正在尝试编写一个读取xml文件的小脚本,然后将我获取的数据导入MySQL数据库。提取工作正常,但插入是一个问题。我和.forEach一起工作以保持asnyc,这对我帮助很大,并且工作正常,直到我需要插入数据。当我尝试在' Loops'之外执行" INSERT" -Query时一切正常,但一旦我尝试在一个内部执行它只需插入一次然后停止。即使没有抛出任何错误,console.log()内的connection.query()消息也不会被执行。

这是我的代码:

console.log("Running import!");

//Import necessary modules
var fs = require("fs"); 
var config = require("./config");
var mysql = require("mysql");
var path = require("path");
var xml2js = require("xml2js");
var parser = new xml2js.Parser();

var connection = mysql.createConnection({
  host     : config.mysql.host,
  user     : config.mysql.user,
  password : config.mysql.password,
  database : config.mysql.db
});

connection.connect(function(err) {
  if (err) { //throw error
    console.error(err.stack);
    throw err;
  }else{
    console.log("Succesfully connected to the database!");
    // Get Folders in Folder and iterate through every of them
    var dirs = getDirectories(config.misc.path);


dirs.forEach(function(dir, index){
    var file = config.misc.path + "\\" + dir + "\\" + config.misc.xml_name;
    // read xml file of that directory
    fs.readFile(file, function(err, data){
        parser.parseString(data, function(err, json){
            if(err) throw err;
            json.resultset.forecast.forEach(function(forecast, index){
                forecast.parking_house.forEach(function(ph, index){
                    var ph_id = ph["$"].id;
                    ph.estimate.forEach(function(estimate, index){
                        var value = estimate.value[0]["_"];
                        var time = estimate.timestamp[0]["_"];
                        //console.log(time);
                        connection.query("INSERT INTO lb_data.estimates VALUES (DEFAULT,'23:00:00', 213, 44);", function(error, results, fields){
                            if(error) throw error;

                            //Printing %
                            var perc = (index / dirs.length * 100);
                            console.log("Scanned and imported " + Math.round(perc) + "% of the files");
                        });
                    });
                });
            });

        });
    });


});
}

  });


/**
 * Gets the direcotries in a directory
 * @param  {string} srcpath the source path of the directory you want to scan
 * @return {void}
 */
function getDirectories (srcpath) {
  return fs.readdirSync(srcpath)
    .filter(file => fs.statSync(path.join(srcpath, file)).isDirectory())
}

提前已经非常感谢! PS:确保config.json中的数据没问题,我已经在循环外测试了,所以这不是问题....

0 个答案:

没有答案