2017-02-16 110 views
0

我想將CSV文件從服務器發送到客戶端。 我有ExpressJS響應從MongoDB獲得的JSON對象。如何在NodeJS和ExpressJS中將嵌套的JSON對象數組轉換爲CSV

這是我的NodeJS代碼,它接受來自客戶端的身份證明和集合名稱參數的發佈請求,在響應中,它提取與這些ID相關的數據。

app.post('/api/v1/imagelist_data/raw-data/:db', function(req, res) { 
    console.log("I received a NEW POST raw-data request"); 
    var dbname = req.params.db; 

    var myarray = req.body._id; 

    // Setting Collection Name 
    var mycollection = db.collection(dbname); 

    // Convert the list of ids to mongo object ids 
    var objectIds = myarray.map(function(item) { 
     return mongojs.ObjectId(item); 
    }); 

    console.log(objectIds); 

    mycollection.find({ 
     _id: { 
      $in: objectIds 
     } 
    }, function(err, docs) { 

     res.json(docs); 


    }); 

現在我在客戶端獲取響應數組對象。 我想用這些對象數組創建一個CSV文件。

對象數組看起來像這樣。

[ 
{ 
    "_id": "58405524d70210dc299ca275", 
    "pictureNumber": 1, 
    "scAttitude": [ 
     0, 
     0, 
     0, 
     1 
    ], 
    "scPosition": [ 
     1, 
     0, 
     0 
    ], 
    "integrationTime": 10, 
    "time": "2016-12-01T16:51:57.000Z", 
    "offset": 1, 
    "gain": 2, 
    "ledStatus": false, 
    "imageType": "Image", 
    "cameraType": "Mongo", 
    "testPatternStatus": false, 
    "temperatureCCD": 189, 
    "temperatureLED1": 162, 
    "temperatureLED2": 152, 
    "temperatureVBG": 490, 
    "temperatureGND": 0, 
    "imageValid": true, 
    "remarks": " Reception time: Thu Dec 01 17:51:47 CET 2016", 
    "imageSize": 2271320 
}, 
{ 
    "_id": "586bc534b31a89bb45b0083e", 
    "pictureNumber": 2, 
    "scAttitude": [ 
     1, 
     0, 
     0, 
     1 
    ], 
    "scPosition": [ 
     1, 
     0, 
     0 
    ], 
    "integrationTime": 20, 
    "time": "2016-12-02T16:51:57.000Z", 
    "offset": 2, 
    "gain": 0, 
    "ledStatus": false, 
    "imageType": "Image", 
    "cameraType": "MOngo", 
    "testPatternStatus": false, 
    "temperatureCCD": 189, 
    "temperatureLED1": 162, 
    "temperatureLED2": 152, 
    "temperatureVBG": 490, 
    "temperatureGND": 0, 
    "imageValid": true, 
    "remarks": " Reception time: Thu Dec 01 17:51:47 CET 2016", 
    "imageSize": 2271320 
}] 

我應該在服務器端還是客戶端進行處理?

我想通過點擊按鈕在客戶端下載帶有數據的CSV文件。

我該如何做到這一點?

回答

0

我的建議是在服務器端生成CSV文件並將其作爲附件返回給客戶端。該方法保證所有設備(筆記本電腦/電話/表格等)上的CSV文件都是相同的。此外,您避免在每個不同的客戶端上重新創建CSV。

響應與expressjs csv文件:

mycollection.find({ 
    _id: { 
     $in: objectIds 
    } 
}, function(err, docs) { 
    if (err) { 
     res.status(400); 
     res.send('Unexpected db error'); 
    } 

    var csv = convertCollectionToCsv(docs); 
    if (!csv) { 
     res.status(400); 
     res.send('Invalid csv format'); 
    } 

    res.attachment('filename.csv'); 
    res.status(200).send(csv); 
}); 

您可以選擇CSV轉換器/分析器第三方庫,或者,如果實在是太簡單,你可以創建自己的。 以下是爲了創建一個CSV文件的典型方法:

var data = getData(); 
 
var csv = convertCollectionToCsv(data); 
 
console.log(csv); 
 

 
function convertCollectionToCsv(docs, seperator) { 
 
    if (!(Array.isArray(docs) && docs.length > 0)) { 
 
    return; 
 
    } 
 

 
    seperator = seperator || ','; 
 

 
    var header = createHeader(docs); 
 
    var body = docs.map(convertObjectsToCsv); 
 
    var csv = [] 
 
    .concat([header]) 
 
    .concat(body) 
 
    .join('\n'); 
 

 
    return csv; 
 

 
    function createHeader(docs) { 
 
    var headRow = docs[0]; 
 
    var header = Object.keys(headRow); 
 
    return header.join(seperator); 
 
    } 
 

 
    function convertObjectsToCsv (doc) { 
 
    // special treatment for dates, nested arrays or objects 
 
    // for instance: 
 
    doc['scAttitude'] = (doc['scAttitude'] || []).join('-'); 
 
    doc['scPosition'] = (doc['scPosition'] || []).join('-'); 
 

 
    var values = getValuesFromObject(doc); 
 
    return values.join(seperator); 
 
    } 
 
} 
 

 
function getValuesFromObject(obj) { 
 
    if (typeof obj !== 'object' || obj === null) { 
 
    return []; 
 
    } 
 

 
    var keys = Object.keys(obj); 
 
    var values = []; 
 
    for (var i = 0; i < keys.length; ++i) { 
 
    values.push(obj[keys[i]]); 
 
    } 
 

 
    return values; 
 
} 
 

 
function getData() { 
 
    return [{ 
 
     "_id": "58405524d70210dc299ca275", 
 
     "pictureNumber": 1, 
 
     "scAttitude": [ 
 
      0, 
 
      0, 
 
      0, 
 
      1 
 
     ], 
 
     "scPosition": [ 
 
      1, 
 
      0, 
 
      0 
 
     ], 
 
     "integrationTime": 10, 
 
     "time": "2016-12-01T16:51:57.000Z", 
 
     "offset": 1, 
 
     "gain": 2, 
 
     "ledStatus": false, 
 
     "imageType": "Image", 
 
     "cameraType": "Mongo", 
 
     "testPatternStatus": false, 
 
     "temperatureCCD": 189, 
 
     "temperatureLED1": 162, 
 
     "temperatureLED2": 152, 
 
     "temperatureVBG": 490, 
 
     "temperatureGND": 0, 
 
     "imageValid": true, 
 
     "remarks": " Reception time: Thu Dec 01 17:51:47 CET 2016", 
 
     "imageSize": 2271320 
 
    }, 
 
    { 
 
     "_id": "586bc534b31a89bb45b0083e", 
 
     "pictureNumber": 2, 
 
     "scAttitude": [ 
 
      1, 
 
      0, 
 
      0, 
 
      1 
 
     ], 
 
     "scPosition": [ 
 
      1, 
 
      0, 
 
      0 
 
     ], 
 
     "integrationTime": 20, 
 
     "time": "2016-12-02T16:51:57.000Z", 
 
     "offset": 2, 
 
     "gain": 0, 
 
     "ledStatus": false, 
 
     "imageType": "Image", 
 
     "cameraType": "MOngo", 
 
     "testPatternStatus": false, 
 
     "temperatureCCD": 189, 
 
     "temperatureLED1": 162, 
 
     "temperatureLED2": 152, 
 
     "temperatureVBG": 490, 
 
     "temperatureGND": 0, 
 
     "imageValid": true, 
 
     "remarks": " Reception time: Thu Dec 01 17:51:47 CET 2016", 
 
     "imageSize": 2271320 
 
    }]; 
 
}

+0

非常感謝。我是新手給JavaScript。當我嘗試在我的應用程序中使用您的代碼時,這兩行代碼給了我錯誤信息。 doc ['scAttitude'] =(doc ['scAttitude'] || [])。join(' - '); doc ['scPosition'] =(doc ['scPosition'] || [])。加入('-'); Object.values不是函數 在convertObjectsToCsv 您能否請幫助。 –

+0

由於瀏覽器的兼容性,Object.values不起作用,https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values。我建議你創建你自己的'getValuesFromObject'函數。 我更新了使用'getValuesFromObject'函數的示例 – Apostolidis

+0

它仍然沒有運行..你可以看看JSFiddle 這裏是鏈接:https://jsfiddle.net/1L3Lv4sv/ –

相關問題