Skip to content

Instantly share code, notes, and snippets.

@rektide
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rektide/326615fbb63f0c0ed4d8 to your computer and use it in GitHub Desktop.
Save rektide/326615fbb63f0c0ed4d8 to your computer and use it in GitHub Desktop.
Domains Module Example
var fs = require('fs'), domain = require('domain')
console.log("\n\n\n\n\n\nHello, welcome to a domain example\n")
// We create three domains, two of which have their own error handler
var d1 = domain.create(), d2 = domain.create(), d3 = domain.create();
[d1,d2].forEach(function(domain, i){
domain.i = i
domain.on('error', function(err) {
console.error("Domain "+err.domain.i+" has a problem!:\n ", err.message)
console.error("We've dealt with the problem\n")
}) })
// Toss a ENOENT to d1
fs.readFile("does-not-exist.txt", "utf8", d1.intercept(function(data){
console.log("We read a file") // except it didn't exist
}))
// Toss an Error to d2
var interval = setInterval(function(){
throw new Error("Interval error")
}, 600)
d2.add(interval);
// All domains throw an error- the third fails!
[d1, d2, d3].forEach(function(domain, i){
domain.run(function(){
setTimeout(function(){
throw new Error("Domain"+(i+1)+" misbehaves")
}, 1000*(i+1))
}) })
Hello, welcome to a domain example
Domain 1 has a problem!:
ENOENT, open 'does-not-exist.txt'
We've dealt with the problem
Domain 2 has a problem!:
Interval error
We've dealt with the problem
Domain 1 has a problem!:
Domain1 misbehaves
We've dealt with the problem
Domain 2 has a problem!:
Domain2 misbehaves
We've dealt with the problem
/Users/Guest/sample.js:26
throw new Error("Domain"+(i+1)+" misbehaves")
^
Error: Domain3 misbehaves
at null._onTimeout (/Users/Guest/sample.js:26:10)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment