如何从返回CSV文件的API中获取数据

时间:2016-05-27 03:44:41

标签: javascript node.js api

我正在使用Pluralsight API,他们的API会将CSV文件作为结果进行响应,我希望从响应中获取这些数据并打印出来。

这是Pluralsight API的网址: https://app.pluralsight.com/plans/api/reports/docs

这是我要做的代码:

  request
    .get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
    .on('response', function (response) {
        res.json(response);
    })

除了以下数据外,响应不会显示任何数据:

  {
  "statusCode": 200,
  "headers": {
    "cache-control": "private",
    "content-disposition": "attachment; filename=Users.csv",
    "content-type": "text/csv",
    "date": "Fri, 27 May 2016 03:42:06 GMT",
    "ps-build": "2016.5.1849.0",
    "ps-node": "0Q5JR",
    "ps-responsetime": "00:00:00.1406230",
    "content-length": "11391",
    "connection": "Close"
  },
  "request": {
    "uri": {
      "protocol": "https:",
      "slashes": true,
      "auth": null,
      "host": "api.pluralsight.com",
      "port": 443,
      "hostname": "api.pluralsight.com",
      "hash": null,
      "search": "?planId=x&token=y",
      "query": "planId=x&token=y",
      "pathname": "/api-v0.9/users",
      "path": "/api-v0.9/users?planId=x&token=y",
      "href": "https://api.pluralsight.com/api-v0.9/users?planId=x&token=y",
    },
    "method": "GET",
    "headers": {}
  }
}

无论如何,我从附件中获取文件并将其解压缩?

由于

1 个答案:

答案 0 :(得分:1)

可以通过dataend事件访问请求正文。

var body = [];
request
    .get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
    .on('data', function (chunk) {
        body.push(chunk);
    })
    .on('end', function () {
        body = body.join('');
        // body now contains csv contents as a string
    });