非同期処理でWebコンテンツをダウンロードする方法5 - IcedCoffeeScript
IcedCoffeeScript は TameJS の await/defer をサポートした CoffeeScript の拡張版です。
前回(id:fits:20120415)、TameJS + CoffeeScript で実装した Web コンテンツのダウンロード処理を IcedCoffeeScript で実装すると以下のようになります。(Embedded JavaScript を使う必要がなくなり、直接 await/defer を使えます)
download_web.coffee (IcedCoffeeScript 版)
http = require 'http' url = require 'url' fs = require 'fs' path = require 'path' dir = process.argv[2] printError = (urlString, error) -> console.log "failed: #{urlString}, #{error.message}" process.stdin.resume() await process.stdin.on 'data', defer(urls) urls.toString().trim().split('\n').forEach (u) -> trgUrl = url.parse u await http.get(trgUrl, defer(res)).on 'error', (err) -> printError u, err res.setEncoding 'binary' buf = '' await res.on 'data', (chunk) -> buf += chunk res.on 'end', defer() res.on 'close', (err) -> printError trgUrl.href, err if err filePath = path.join dir, path.basename(trgUrl.pathname) await fs.writeFile filePath, buf, 'binary', defer(err) if err printError trgUrl.href, err else console.log "downloaded: #{trgUrl.href} => #{filePath}"
サンプルソースは http://github.com/fits/try_samples/tree/master/blog/20120716/
インストール方法は以下の通りです。
IcedCoffeeScript インストール
npm install -g iced-coffee-script
実行は iced コマンドで直接実行できます。(TameJS + CoffeeScript 版のような変換処理が必要ありません)
実行例
iced download_web.coffee destdir < urls.txt