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 我只是想问一下,所以有人可以帮我看看。我不认为这是一个很长的脚本 –