javascript - 使用 NodeJS 解析雅虎财经 CSV

标签 javascript node.js csv

我正在尝试解析来自雅虎财经的一个非常简单的 csv 文件。生成的 csv 仅包含股票的当前价格。当我运行这个时,我不断收到此错误。我的语法有问题吗?

/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)})})

最佳答案

我认为这可以完成您的下载。它基于此解决方案并需要重定向处理

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());
  }
})

关于javascript - 使用 NodeJS 解析雅虎财经 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172095/

相关文章:

java - 使用java将多个csv文件合并为一个文件?

javascript - 从 JSP If 语句调用 jQuery 函数

javascript - 如何向具有特定 ID 的 channel 发布公告?

c# - 我如何在 javascript 警告对话框中添加标题文本

javascript - 无法在vue js组件中导入js-search

node.js - 警告 : Each child in a list should have a unique "key" prop. %s%s

javascript - 从 vb6 调用 javascript 函数

javascript - 有没有办法在终止时触发快速应用程序中的功能?

Python,字典到 CSV : is there a faster way to do it?

Python - 匹配和更改日期时间