0
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。

4

1 回答 1

1

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

你在这里做了很多已经完成的工作。

于 2013-01-23T17:35:49.233 回答