使用NodeJS解析Yahoo Finance CSV

时间:2016-12-15 19:40:03

标签: javascript node.js csv

我正在尝试从yahoo finance解析一个非常简单的csv文件。由此产生的csv只有股票的当前价格。当我运行这个时,我继续得到这个错误。我的语法中有什么东西吗?

  

/ tmp / de49fef0-c2fb-11e6-b1be-07e013ca5c3c / Node Application / app.js:6   https.get(endpoint,(response)=> {^ SyntaxError:意外的令牌>   在Module._compile(module.js:437:25)处于Object.Module._extensions..js   (module.js:467:10)在Module.load(module.js:356:32)at   Module.runMain中的Function.Module._load(module.js:312:12)   (module.js:492:10)at   process.startup.processNextTick.process._tickCallback(node.js:244:9)

var https = require('https')

var endpoint = "http://finance.yahoo.com/d/quotes.csv?s=AAPL&f=a" 

var body = ""
https.get(endpoint, (response) => {
              response.on('data', (chunk) => { body += chunk })
              response.on('end', () => {
              var data = JSON.parse(body)
console.log(data)})})

1 个答案:

答案 0 :(得分:1)

我认为这会进行下载。它基于此解决方案,需要重定向处理

How to download a file with Node.js (without using third-party libraries)?

var http = require('http');
var fs = require('fs');

var endpoint = "http://finance.yahoo.com/d/quotes.csv?s=AAPL&f=a"

var body = ""

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    if(response.statusCode === 301){
      console.log();
      var request = http.get(response.headers.location, function(response) {
        response.pipe(file);
        file.on('finish', function() {
          file.close(cb);  // close() is async, call cb after close completes.
        });
      });
    }
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};


download(endpoint, 'test.csv', function(err){
  if(err){
    console.log(err);

  }
  else{
    //read csv file here
    console.log(fs.readFileSync('test.csv').toString());
  }
})