Billy Troll
Billy Troll

Reputation: 3

Nodejs - need explanation

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'])

There is no problem with fetch and download function since the file is downloaded file. This code is supposed to return the image to browser, but it instead returns a bunch of json stuffs http://pastebin.com/23CWicgB . When I tried to use node-inspector and node to debug, the result was somehow binary but I still don't know why it returns json.

Upvotes: 0

Views: 218

Answers (1)

astone26
astone26

Reputation: 1232

If you're interested in returning an image to the user over HTTP: Consider using a framework to deal with these request. Express.js seems to be a standard in the NodeJS community.

You're doing a lot of work here that has already been done.

Upvotes: 1

Related Questions