Skip to content

Instantly share code, notes, and snippets.

@katoy
Created January 16, 2013 09:32
Show Gist options
  • Save katoy/4545871 to your computer and use it in GitHub Desktop.
Save katoy/4545871 to your computer and use it in GitHub Desktop.
sample using domain API.
これはテストデータです。
# node.js : 0.8.17
domain = require 'domain'
fs = require 'fs'
# ファイルが存在しない時に catch できない。
#---------------------------------------------
func1 = (filename) ->
try
fs.readFile filename, 'utf8', (err, data) ->
throw "Func 1: #{filename}: #{err}" if (err)
console.log 'Func1 OK: ' + filename
console.log data
catch err
console.error "Func1: Caught error! #{err}"
# ファイルの存在を明示的にチェックするようにする。
# でも filename に folder が指定された時に catch できない。
#---------------------------------------------
func2 = (filename) ->
try
unless fs.existsSync filename
throw new Error("Func2: File can not open: #{filename}")
else
fs.readFile filename, 'utf8', (err, data) ->
throw "Func2: #{filename} #{err}" if (err)
console.log 'Func2 OK: ' + filename
console.log data
catch err
console.error "Func2: Caught error! #{err}"
# domain をつかって、簡素に!
# ファイルが存在しない、フォルダを指定された時も catch できている。
#---------------------------------------------
func3 = (filename) ->
d.run ->
fs.readFile filename, 'utf8', (err, data) ->
throw "Func3: #{filename}: #{err}" if (err)
console.log 'Func3 OK: ' + filename
console.log data
#--------------------------------------------------------
d = domain.create()
d.on "error", (err) ->
console.error "Func3: Caught error! #{err}"
filename = 'data.txt'
no_name = 'no-exists.txt'
foldername = '.'
func1(filename)
func2(filename)
func3(filename)
#func1(no_name)
func2(no_name)
func3(no_name)
#func1(foldername)
#func2(foldername)
func3(foldername)
# ------------ Running result -----------
# $ coffee domain-sample.coffee
# Func2: Caught error! Func2: Error: File can not open: no-exists.txt
# Func3: Caught error! Func3: no-exists.txt: Error: ENOENT, open 'C:\zzz\misc\no-exists.txt'
# Func1 OK: data.txt
# これはテストデータです。
#
# Func2 OK: data.txt
# これはテストデータです。
#
# Func3 OK: data.txt
# これはテストデータです。
#
# Func3: Caught error! Func3: .: Error: UNKNOWN, read
# -------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment