17Nov

node23_2

So, we continue our lesson. Let us make this example a little bit more complicated by adding work with the files in the following way:

var domain = require('domain');
var fs = require('fs');
var d = domain.create(), server;

d.on('error', function(err) {
    console.error("Domain has caught %s", err);
});


d.run(function() {

    setTimeout(function() {
      fs.readFile(__filename, function() {
          ERROR();
      });
        }, 1000);

});

Launch it. Interesting to notice, but the system still works. Why? How did the domain from this function moved to fs.readFile(__filename, function()? The answer is the same. It happens because internal implementation of the function readFile knows about domains. When it launches a callbackit does it within the same domain context. It guarantees this success.

Let us look at our last example. Create a new object:

server = new http.Server();

the whole logics generating an error will be inside the event handler:

server.on('boom', function() {
    setTimeout(function() {
        fs.readFile(__filename, function() {
            ERROR();
        });
    }, 1000);
});

And in order to make it even more complicated, let us place this code below. It means, we create an object in one place, and an error will occur after we’ve already launched the domain. Will the domain handle it? So, let us launch our code, it will look like this in its full form:

var domain = require('domain');
var fs = require('fs'), http = require('http');

var d = domain.create(), server;

d.on('error', function(err) {
    console.error("Domain has caught %s", err);
});

d.run(function() {

    server = new http.Server();

});

server.on('boom', function() {
    setTimeout(function() {
        fs.readFile(__filename, function() {
            ERROR();
        });
    }, 1000);
});

server.emit('boom');

As we can see, everything was successfully handled. But how did this function know about the domain? It happened thanks to integration. The server is EventEmitterThis module knows about domains, and whenever any EventEmitter is created – whether there is a current active domain – it receives a link to it, where you can output it. Add  console.log:

server = new http.Server();  
console.log(server.domain); 

Launch it. Well done. Once EventEmitter is connected to a domain, it launches any handler within the context of this domain. Of course, if a server is created outside an active domain, there is no way for server.domain to exist. However, you can still work with such objects; you only need to add their domain manually using a special call add:

server = new http.Server();

d.run(function() {

    d.add(server);

    console.log(server.domain);

});

If we call it now, everything will be great, an error is caught. The only thing here we should consider is the memory control. The reason is that if EventEmitter is created within a domain context, it receives a link – in our case, server.domainBut if it has been created earlier and added via addit receives not only the very link to this domain, but the domain itself shows a link to it. It means, the domain has got a special array named members, where it refers to everything that is referred through addHowever, that’s how the current implementation looks like. Respectively, we’ve got a bilateral reference with add – server ↔domain. As a result, we see that memory can be cleaned not from a server or a domain separately, but from both of them. It means, if there is some long-existing domain and we add a lot of things to it via add , the memory won’t be cleaned until the domain dies or until there is a call d.remove(server) whenever it’s possible. Generally, these things are rarely used within scripts. Developers usually try to create everything you may need inside a domain in order to avoid such problems.

So, let us get back to an example from the first part of this article, i.e. to the server. Move to commit with the name domain_1-11:

So, what do you think is the reason? Why did a request handler error occur, but wasn’t handled by the domain? How can we fix it? The reason is that the sever was created outside the domain. So, handler  deals with an event request. Since the server was created outside the domain, no domain is transferred in case of a handler call, and throw, as it has been before, fails the whole process. In order to fix everything, we only need to take the server and create it within the call run:

serverDomain.run(function() {  
  var server = require('./server');  
  server.listen(3000);  
});

So, it will be ok this way, as the server is connected to the domain. Let us check the result. Launch the code. Call Chrome and follow the same url:

http://127.0.0.1:3000/

Now the domain has caught an error, the system hasn’t failed. On the other hand, a task may not be considered to be fully solved because we need to respond something to a visitor: “Sorry, and error occurred. Return to the page later.”

And how should we respond? Here server.domain caught an error, but it has no information on where it is contained. In order to receive it, we will create a domain separately for every request. It may look the following way. There are two files. The first one, app.js, is the main file of our app:

var domain = require('domain');
var serverDomain = domain.create();

var server;

serverDomain.on('error', function(err) {
   console.error("Server error", err);
   if (server) server.close();

   setTimeout(function () {
       process.exit(1);
   }, 1000).unref();
});


serverDomain.run(function() {
    var http = require('http');
    var handler = require('./handler');
    //var database = require ('mongodb');

     server = http.createServer (function(req, res) {

       var reqDomain = domain.create();
        reqDomain.add(req);
        reqDomain.add(res);

        reqDomain.on('error', function(err) {
          res.statusCode = 500;
          res.end("Sorry, " + err);
           // ...
          serverDomain.emit('error', err);
        });

        reqDomain.run(function() {
           handler(req, res);
         });
       });

     server.listen(3000);
});

It launches a server, creates domains. The second one, handler.js is a module that handles requests:

var fs = require('fs');

module.exports = function handler(req, res) {
    if (req.url == '/') {

        fs.readFile('no-such-file', function(err, content) {

            if (err) throw err; // JSON.parse("invalid!")

            res.end(content);
        });

    } else {
        res.statusCode = 404;
        res.end("Not Found");
    }

};

So, what does app.js include?

We will talk about this later, in our next article. See you soon!

This lesson’s code can be found here.

to-be-continued-series-8

The materials for this article were borrowed from the following screencast.

We are looking forward to meeting you on our website soshace.com

One Reply to “23. Node.js Lessons. Domains, asynchronous try.. catch. Part 2.”

  1. avi tshuva 8 years ago

    i’d have really recommend you to re-write the article and base it on zones, since domains are long deprecated…

Leave a Reply