Node.js 获取yahoo股票csv数据并封闭成为接口输出json数据

思路

紧跟着前两篇的Node.js 生成微信数字签名[SHA1算法]添加多一个路由为/stock和相应的处理函数,先从yahoo接口获取数据,再转化成为json输出。

requestHandlers.js 文件添加处理函数代码

exports.stock = (res, req) => {
  const arg = url.parse(req.url, true).query
  const stockName = arg.stockname
  const startDateArr = arg.startdate.split('-')
  const endDateArr = arg.enddate.split('-')
  const startY = startDateArr[0]
  const startM = startDateArr[1] - 1
  const startD = startDateArr[2]
  const endY = endDateArr[0]
  const endM = endDateArr[1] - 1
  const endD = endDateArr[2]
  const stockAPI = 'http://table.finance.yahoo.com/table.csv?s=' + stockName + '&f=' + endY + '&d=' + endM + '&e=' + endD + '&c=' + startY + '&a=' + startM + '&b=' + startD + '&g=d&ignore=.csv' // 定义stock api的url
  let resultStr = ''
  http.get(stockAPI, response => {
    response.on('data', data => {
      resultStr += data
    })
    response.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'application:json' })
      res.write(JSON.stringify(csv2json(resultStr)))
      res.end()
    })
  }).on('error', e => {
    console.error(e)
  })
}

function trim(str){ // 删除左右两端的空格
 return str.replace(/(^\s*)|(\s*$)/g, '')
}

function csv2json(str){
  let jsonArr = []
  str = trim(str)
  const lines = str.split('\n')
  if(lines.length > 1){
    const heads = lines[0].split(',')
    for(var i=1; i < lines.length; i++){
      let obj = {}
      let temArr = lines[i].split(',')
      for(let j=0; j < heads.length; j++){
        obj[heads[j]] = temArr[j];
      }
      jsonArr.push(obj);
    }
  }
  return jsonArr
}

index.js添加路由代码

handle['/stock'] = requestHandlers.stock

 

作者: 博主

Talk is cheap, show me the code!

发表评论

电子邮件地址不会被公开。

Captcha Code