Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Recruitment

    Optimizing Recruitment: Best Practices for Employers and Candidates

    Interview

    Interview with “Soshace” team

    Startups

    Strategies for Maintaining Agility in Your Startup’s Growth

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 23. Node.js Lessons. Domains, asynchronous try.. catch. Part 1.
    Programming

    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 1.

    Ivan RastvorovBy Ivan RastvorovNovember 17, 2016Updated:May 26, 2024No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 1.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    node-24-part_1

    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.

    Read More:  Angular 2, part 1

    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:

    Read More:  Web Developer Portfolio: The Definitive 2019 Guide with 15 Portfolio Examples

    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.

    futurecontinued

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

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

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Programming August 9, 2016

    Short React Story

    Today we want to talk about front-end technology that nowadays, is becoming more and more popular.

    It’s name React, created by a collaboration of Facebook and Instagram to make pretty fast job, while you are working on a front-end. Last year we were watching how most of our clients started their new projects, and refactored some old one using it.

    Building a serverless web application with Python and AWS Lambda

    May 8, 2023

    Managing Kubernetes using Terraform

    March 16, 2021

    Уроки React. Урок 12.

    November 1, 2016

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    JavaScript Design Patterns in Action

    JavaScript January 2, 2020

    Project Manager Role

    JavaScript June 1, 2016

    Node.js Lesson 17: Timers, Differences from Browser, ref and ref

    Node.js March 9, 2021

    Automating and Scheduling Tasks Using Python

    Beginners October 19, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Lead Generation

    Why Most MSPs Fail at Lead Generation (And How to Fix It)

    Events

    Two 2017 Collaboration Software Awards Now Belong To Soshace

    Beginners

    11 Best Books on DevOps: Comprehensive Overview

    Most Popular

    Build a Python Command-line Program Using OOP

    Python

    Contentful+Gatsby = Smarter content management

    JavaScript

    Tough Interview

    Comics
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.