Hey all! Our topic for today is Domains.
Domains are one of the Node.js options lacking both in standard JavaScript and browser versions of JavaScript. Domains were created to catch any asynchronous errors. For instance, if we look at the server that we’ve explored in one of our previous articles (download the lesson code from here for your convenience), we will see that everything is ok when it’s working
var http = require('http'); var fs = require('fs'); function handler(req, res) { if (req.url == '/') { fs.readFile('index.html', function(err, content) { if (err) { console.error(err); res.statusCode = 500; res.end('There is an error on the server'); return } res.end(content); }); } else { res.statusCode = 404; res.end("Not Found"); } } var server = new http.createServer(handler); server.listen(3000);
But whenever some program error occurs – let’s imagine, a call of an unknown function:
fs.readFile('index.html', function(err, content) { if (err) { blabla(); console.error(err); res.statusCode = 500; res.end('There is an error on the server'); return } res.end(content);
or a user puts throw
instead of handling the error:
fs.readFile('index.html', function(err, content) { if (err) throw err; res.end(content); });
Or some sort of a program error – for example, a call of JSON.parse("invalid!")
with invalid JSON
, which crashes the whole process in the end. It turns out, we’ve got a server with 1000 clients connected to it, and a program error occurs when handling a request from one of them:
if (err) throw err;//JSON.parse("invalid!")
The current state leads to a crash of the whole process. Of course, it is bad because every process crash means a connection failure for all previously connected clients. If a server crashes, let us at least handle it in a proper way, show a message that an error occurred, and only after it, if the error is crucial, we can intercept the process. But this task is quite difficult, even though being essential and obligatory for to be solved.
For the reason callbacks
function(err, content)
are called asynchronously, wrapping in try... catch
is generally absolutely ineffective here. So, let us add this record to our code instead of the current one:
var server = new http.createServer(function (req, res) { try { handler(req, res); } catch(err) { //error! } }); server.listen(3000);
Even if we call a handler inside try... catch
, it will be able to catch only those errors present for the current work of a handler
function. But if there are some asynchronous callbacks
, they are not included.
Now, when we know something about the problem, let us talk about possible ways to solve it in Node.js. To do so, we need to use a module named domain
. At the moment, this module is obsolete and using it in the current version of Node.js (7.1) is not recommended. Our articles about domains will be useful for understanding and working with Legacy Code for example. It will enable us to create a special object called a “domain” – for example, serverDomain
, and let us add it to our server.js
:
var domain = require('domain'); var serverDomain = domain.create();
In the domain context you can launch functions, and it will catch any possible error, including an asynchronous one, which may happen within the function or one derived from it. As an example, let us do some refactoring
of the current code inside the file server.js
by completing export of the server, and launch it from the other domain-contained file:
var http = require('http'); var fs = require('fs'); 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"); } } var server = new http.createServer(handler); module.exports = server;
A new file being launched will be called app.js, add it to the root directory. It will create a domain
object and connect a server:
var domain = require('domain'); var serverDomain = domain.create(); var server = require('./server'); serverDomain.on('error', function(err) { console.error("Domain has caught %s", err); }); serverDomain.run(function() { server.listen(3000); });
A server is simply being exported from the file server.js
. It means, it doesn’t launch a server at the moment, but simply creates it.
Next we install a domain
handler in app.js
serverDomain.on('error', function(err) { console.error("Domain has caught %s", err); });
Any error that will occur inside the domain will be caught by this function. And, finally, the most important thing – let us launch a server inside the domain using a special call named run
:
serverDomain.run(function() { server.listen(3000); });
Now any error occurring as a result of work of a previous function or a function derived from it, including handlers, will be caught. So, let us launch a project and then launch it once again. As the address is already occupied, it led to an error, which means a server showed an error
event:
Domain has caught Error: listen EADDRINUSE :::3000
For the reason there were no handlers for this error
, this event would lead to an exception that would fail the process, but now it is successfully caught by the domain.
Let us try to access an unknown file:
fs.readFile('no-such-file', function(err, content) {
Launch app.js
, follow this url in Chrome:
http://127.0.0.1:3000/
Enter. Error. That’s what has happened: for some reason we’ve got an exception, our domain
didn’t work. Why? Here we see one of the downsides domains have. To understand and fix it, let us see how domains work and why domain failed in this situation. It will be easier to understand domains, if we look at a couple of simple examples followed by a more complex example, instead of one too complicated case. So, let us create domain.js
with this code (other files may be deleted):
var domain = require('domain'); var d = domain.create(), server; d.on('error', function(err) { console.error("Domain has caught %s", err); }); d.run(function() { ERROR(); });
Here in domain
we see a function launched, and we don’t know exactly what it calls. So, launch it. Domain
caught an error:
Domain has caught ReferenceError: ERROR is not defined
How did it manage to do it? Everything’s quite simple. Whenever a function is called in d.run
, it is surrounded by implicit try catch
. Respectively, any exception derived from this function immediately turns into an error:
d.on('error', function(err) { console.error("Domain has caught %s", err); });
That is the most trivial case. But let us study something more difficult by changing our code in domain.js
in the following way:
var domain = require('domain'); var d = domain.create(), server; d.on('error', function(err) { console.error("Domain has caught %s", err); }); d.run(function() { setTimeout(function() { ERROR(); }, 1000); });
Here the same function with an error is called inside setTimeout
. So, check whether it works. It does! But how does this function inside setTimeout
get to know it is launched inside the domain? You can answer this question, if you look inside Node.js. When a function is launched in the domain
context, there occurs a special call inside the domain
module before the launch:
d.enter();
and a call in the end,
//d.exit();
or the domain
enter and exit:
.run(function() { // d.enter(); setTimeout(function() { ERROR(); }, 1000); // d.exit(); });
And this:
setTimeout(function() { ERROR(); }, 1000);
will work asynchronously one day. It will get a domain
for the reason that whenever we enter the domain
, its current object becomes global. It looks just like that:
d.run(function() { // d.enter(); -> process.domain
And setTimeout
, just like a number of other Node.js modules responsible for various asynchronous things, is integrated into domains. It means, the setTimeout
internal implementation analyzes whether there is an active current domain
, and upon calling the function it guarantees the very domain
will be active. So, if you create a console inside the function:
setTimeout(function() { console.error(process.domain); ERROR(); }); }, 1000);
We will get it by launching domain.js
:
Domain { domain: null, _events: { error: [Function] }, _eventsCount: 1, _maxListeners: undefined, members: [] } Domain has caught ReferenceError: ERROR is not defined
Note, it is a standard object that inherits EventEmitter
.
To be continued!
The lesson code can be found here.
The materials for this article were borrowed from the following screencast.
We are looking forward to meeting you on our website soshace.com
That’s a very good, clearly written article!
It is important to note that the domain module is deprecated and it is replaced by **zones**
You can read a lot about it there: https://github.com/nodejs/CTC/issues/4