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 stuffs http://pastebin.com/23CWicgB。當我試圖使用節點檢查器和節點進行調試時,結果以某種方式進行二進制處理,但我仍然不知道它爲什麼會返回json。Nodejs - 需要說明
你能告訴我們你看到什麼*症狀嗎? 「我的代碼有什麼問題?」這不是一個好問題。 –
我認爲這屬於codereview – jsj
@JoachimSauer實際上,我真的不知道這個代碼行有什麼問題T_T 我只是想問一下,所以有人可以幫我看看。我不認爲這是一個很長的腳本 –