Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js domain Module

Node.js Domain Module

Java FileNode.js Built-in Modules


The Domain module is a tool in Node.js for simplifying error handling in asynchronous code. It allows you to group multiple asynchronous operations into a "domain" and uniformly capture and handle errors within that domain.

In simple terms, a Domain is like an error-handling "container": you can put related asynchronous operations into this container and then uniformly manage the errors these operations may produce.

The use of the domain module was deprecated in Node.js 14, because the Node.js community recommends more modern ways to handle errors, such as using async/await or more comprehensive error listening and handling logic.


Why Is the Domain Module Needed?

In Node.js asynchronous programming, error handling can become complex:

  1. Asynchronous Errors Are Hard to Catch: Traditional try-catch cannot catch errors in asynchronous callbacks
  2. Error Propagation Is Difficult: Errors can occur in any asynchronous operation, making them hard to trace to their source
  3. Resource Cleanup Issues: After an error occurs, you need to ensure resources are properly released

The Domain module was designed to solve these problems.


Core Concepts of the Domain Module

1. Creating a Domain

Example

const

domain

=

require

(

'domain'

)

;

const

myDomain

=

domain.

create

(

)

;

2. The Domain Lifecycle

  1. creation: When using domain.create()
  2. Enter: When using domain.enter() or implicit entry
  3. Run: Execute code within the domain
  4. Exit: When using domain.exit()
  5. Destroy: Automatically destroyed when there are no references

3. Implicit Binding

A Domain can be implicitly bound to the following objects:


Main Methods of Domain

1. domain.run(fn)

Execute a function in the domain context:

Example

myDomain.

run

(

(

)

=>

{

 

// Asynchronous operations here will be captured by the domain

  setTimeout

(

(

)

=>

{

   

throw

new

Error

(

'Async error'

)

;

 

}

,

100

)

;

}

)

;

2. domain.add(emitter)

Explicitly add an EventEmitter instance to the domain:

Example

const

server

=

require

(

'http'

)

.

createServer

(

)

;

myDomain.

add

(

server

)

;

3. domain.remove(emitter)

Remove an EventEmitter instance from the domain.

4. domain.bind(callback)

Return a new function bound to the domain:

Example

const

boundFn

=

myDomain.

bind

(

(

err

,

data

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

data

)

;

}

)

;

5. domain.intercept(callback)

Similar to bind, but specifically handles error-first callbacks:

Example

const

interceptedFn

=

myDomain.

intercept

(

(

err

,

data

)

=>

{

  console.

log

(

data

)

;

}

)

;


Error handling

Domain handles captured errors through the error event:

Example

myDomain.

on

(

'error'

,

(

err

)

=>

{

  console.

error

(

'Domain caught error:'

,

err

)

;

 

// Clean up resources

  server.

close

(

)

;

}

)

;


Practical Application Examples

1. HTTP Server Error Handling

Example

const

http

=

require

(

'http'

)

;

const

domain

=

require

(

'domain'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

const

d

=

domain.

create

(

)

;

 

  d.

on

(

'error'

,

(

err

)

=>

{

    res.

statusCode

=

500

;

    res.

end

(

`Server error

:

$

{

err.

message

}

`

)

;

   

// Prevent process crashes

    server.

close

(

)

;

 

}

)

;

 

  d.

run

(

(

)

=>

{

   

// Handle requests

    process.

nextTick

(

(

)

=>

{

     

// Simulate an asynchronous error

     

if

(

req.

url

===

'/error'

)

{

       

throw

new

Error

(

'Intentional error'

)

;

     

}

      res.

end

(

'OK'

)

;

   

}

)

;

 

}

)

;

}

)

;

server.

listen

(

3000

)

;

2. Database Connection Management

Example

const

domain

=

require

(

'domain'

)

;

const

db

=

require

(

'some-db-library'

)

;

function

queryDatabase

(

callback

)

{

 

const

d

=

domain.

create

(

)

;

 

  d.

on

(

'error'

,

(

err

)

=>

{

    console.

error

(

'Database error:'

,

err

)

;

    db.

releaseConnection

(

)

;

 

}

)

;

 

  d.

run

(

(

)

=>

{

    db.

getConnection

(

(

err

,

connection

)

=>

{

     

if

(

err

)

throw

err

;

     

      connection.

query

(

'SELECT * FROM users'

,

(

err

,

results

)

=>

{

       

if

(

err

)

throw

err

;

        callback

(

null

,

results

)

;

        db.

releaseConnection

(

)

;

     

}

)

;

   

}

)

;

 

}

)

;

}


Limitations of Domain

  1. Deprecated: Node.js has officially deprecated the domain module; async_hooks or other methods are recommended
  2. Memory Leaks: Incorrect use may cause memory leaks
  3. Performance overhead: Creating and managing domains has a certain performance overhead

Alternatives

Since the domain module has been deprecated, consider the following alternatives:

  1. async/await + try-catch: Use modern JavaScript asynchronous patterns
  2. Promise Error Handling: When using .catch() Handle errors in Promise chains
  3. async_hooks: A lower-level asynchronous context-tracking API provided by Node.js

Methods and Properties

Method/attribute Description
domain.create() Creates and returns a new domain instance.
domain.run(callback) Runs the provided callback function within the domain, automatically capturing errors inside that callback.
domain.bind(callback) Creates a new function that calls the original function while capturing any thrown errors.
domain.intercept(callback) Similar to bind(), but passes the error as the first argument to the callback function.
domain.add(emitter) Explicitly adds an EventEmitter or Timer object so that its errors are captured by the current domain.
domain.remove(emitter) Removes the specified EventEmitter or Timer object from the domain.
domain.on('error', callback) Listens for the error event within the domain, capturing all unhandled errors.

Example

** 1. Creating a Domain and Using domain.run() to Capture Errors**

domain.run() can place asynchronous operations into a domain; if an error occurs in an operation, it will be captured and handled by the current domain.

Example

const

domain

=

require

(

'domain'

)

;

const

d

=

domain.

create

(

)

;

d.

on

(

'error'

,

(

err

)

=>

{

  console.

log

(

'Error captured:'

,

err

)

;

}

)

;

d.

run

(

(

)

=>

{

  setTimeout

(

(

)

=>

{

   

throw

new

Error

(

'Asynchronous error'

)

;

 

}

,

100

)

;

}

)

;

In the example above, the error inside setTimeout is captured by the error event of domain d, without causing the process to crash.

** 2. Using domain.bind() to Capture Errors in Callbacks**

domain.bind() creates a wrapper function that can capture errors in a callback function into the current domain.

Example

const

domain

=

require

(

'domain'

)

;

const

d

=

domain.

create

(

)

;

d.

on

(

'error'

,

(

err

)

=>

{

  console.

log

(

'Error captured:'

,

err

)

;

}

)

;

const

asyncFunction

=

d.

bind

(

(

callback

)

=>

{

  setTimeout

(

(

)

=>

{

    callback

(

new

Error

(

'Error in callback'

)

)

;

 

}

,

100

)

;

}

)

;

asyncFunction

(

(

err

)

=>

{

 

if

(

err

)

throw

err

;

}

)

;

Here, the error in asyncFunction is captured and handled by the domain.

** 3. Using domain.add() to Explicitly Add Events**

You can use domain.add() to add a specific EventEmitter to the domain so that its errors are also captured by that domain.

Example

const

domain

=

require

(

'domain'

)

;

const

EventEmitter

=

require

(

'events'

)

;

const

d

=

domain.

create

(

)

;

const

emitter

=

new

EventEmitter

(

)

;

d.

on

(

'error'

,

(

err

)

=>

{

  console.

log

(

'EventEmitter error captured:'

,

err

)

;

}

)

;

// Add the emitter to the domain

d.

add

(

emitter

)

;

emitter.

on

(

'data'

,

(

)

=>

{

 

throw

new

Error

(

'Error in EventEmitter'

)

;

}

)

;

emitter.

emit

(

'data'

)

;

When the data event throws an error, the domain captures it without causing the program to crash.

Notes and Limitations of domain

Alternatives

Because domain has been deprecated; the following approaches are recommended for handling errors in asynchronous operations:

Although domain The module provides a convenient way to capture errors in asynchronous operations, but due to its performance and reliability issues, Node.js officially does not recommend using it in new projects. For exception handling, more modern solutions are recommended, such as async/await and event listeners, ensuring errors can be effectively handled in the application.

Java FileNode.js Built-in Modules