Nodejs - 需要解释

时间:2012-09-03 05:15:04

标签: node.js coffeescript

http = require('http')
https = require('https')
fs = require('fs')
url = require('url')
req = require('request')
server = require('node-router').getServer()

# run server
server.listen process.env.PORT || 8080, '0.0.0.0'

# stop the error
server.get "/favicon.ico", (req, res)->
  return ""

# display image
server.get(new RegExp("^/(.*)(?:.jpg)?$"), (req, res, match) ->

  download(match, output, ()->
    img = fs.readFile(output, (err, data)->
      res.writeHead(200, {'Content-Type' : 'image/jpeg'})
      res.end(data, 'binary')
    )
  )
)

# download image to our host
download = (match, output, callback) ->

  #fetch
  fetch(match, (p_url)->
    #save file
    uri = url.parse(p_url)
    host = uri.hostname
    path = uri.pathname

    if uri.protocol == "https:"
      r = https
    else
      r = http

    r.get host:host, path:path, (res)->
      res.setEncoding 'binary'

      img=''
      res.on 'data', (chunk)->
        img+=chunk

      res.on 'end', ()->
        fs.writeFile output, img, 'binary', (err)->
          callback()
  )

# fetch image from google images
fetch = (query, cb) ->
  uri = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q=' + encodeURI(query)

  req {uri: uri}, (e, res, body) ->
    res = JSON.parse(body)['responseData']['results'][0]
    unless res
      cb("https://img.skitch.com/20110825-ewsegnrsen2ry6nakd7cw2ed1m.png")
    cb(res['unescapedUrl'])

由于文件是下载文件,因此获取和下载功能没有问题。这段代码应该将图像返回给浏览器,但它会返回一堆json东西http://pastebin.com/23CWicgB。当我尝试使用node-inspector和node进行调试时,结果以某种方式二进制,但我仍然不知道它为什么返回json。

1 个答案:

答案 0 :(得分:1)

如果您对通过HTTP将图像返回给用户感兴趣: 考虑使用框架来处理这些请求。 Express.js似乎是NodeJS社区的标准。

你们已经在这里做了很多工作。