0

I am trying to parse a very simple csv file from yahoo finance. The resulting csv just has the current price of the stock. When I am running this I keep on getting this error. Ss there something off in my syntax ?

/tmp/de49fef0-c2fb-11e6-b1be-07e013ca5c3c/Node Application/app.js:6 https.get(endpoint, (response) => { ^ SyntaxError: Unexpected token > at Module._compile (module.js:437:25) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.runMain (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)})})
zengr
  • 38,346
  • 37
  • 130
  • 192
rustyocean
  • 233
  • 5
  • 14

1 Answers1

1

I think this will do your download. It is based on this solution and require Redirect handling

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());
  }
})
Community
  • 1
  • 1
Lucas Katayama
  • 4,445
  • 27
  • 34