如何将查询数据添加到数组

时间:2019-04-02 14:44:31

标签: javascript node.js

我正在尝试使用对REST端点的查询来遍历数据,然后将其添加到数组中并将其写出到csv tempArray中为空end

var fastcsv = require('fast-csv');  
var tempArray=[];
conn.login(logincred, loginpass, function(err, res) {
    fastcsv.fromPath("accounts.csv").on("data", function(csvrow){
        conn.query("SELECT Id, Name, PersonEmail FROM Account WHERE PersonEmail = '" + csvrow[2] + "' LIMIT 1" , function(err, res) {
            if (err){ 
                console.log(err);
            }
            csvrow[3] = res.records[0].Id
            tempArray.push(csvrow);
            console.log(tempArray)
        });
    }).on('end',function() {
        console.log('CSV file successfully processed');
        console.log(tempArray)
        //want to write csv here
    });
});

2 个答案:

答案 0 :(得分:0)

就fast-csv中的文档而言,应该只是这样:

var fastcsv = require('fast-csv');  
var tempArray=[];
conn.login(logincred, loginpass, function(err, res) {
    fastcsv.fromPath("accounts.csv").on("data", function(csvrow){
        conn.query("SELECT Id, Name, PersonEmail FROM Account WHERE PersonEmail = '" + csvrow[2] + "' LIMIT 1" , function(err, res) {
            if (err) {
                console.log(err);
            }
            csvrow[3] = res.records[0].Id
            tempArray.push(csvrow);
            console.log(tempArray)
        });


    })
    .on('end',function() {
        console.log('CSV file successfully processed');
        console.log(tempArray)
        fastcsv.writeToPath("whatever.csv", tempArray, {headers: true})
            .on("finish", function() {
                console.log("done!");
            });
    });
});

您可以使用此小型节点程序尝试编写代码:

var csv = require('fast-csv');
var tempArray = [['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']];
csv.writeToPath("./whatever.csv", tempArray, {headers: true})
    .on("finish", function() {
        console.log("done!");
    });

答案 1 :(得分:0)

我整理出尼尔森是对的,这基本上是一场比赛。我把'end'夹在conn.query()循环中的效果更好。

    fastcsv.fromPath("accounts.csv").on("data", function(csvrow){
        conn.query("SELECT Id, Name, PersonEmail FROM Account WHERE PersonEmail = '" + csvrow[2] + "' LIMIT 1" , function(err, res) {
            if (err) {
                console.log(err);
            }
            csvrow[3] = res.records[0].Id
            tempArray.push(csvrow);
            fastcsv.writeToPath("new.csv", tempArray, {headers: true})
            .on("finish", function() {
                console.log("Added : " + csvrow[2]);
            });
        });
    })