Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

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

    Recruitment

    Maximizing Hiring Efficiency: A Guide to Recruitment Software

    Comics

    Search of Investments

    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
    Monday, September 29
    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 2.
    Programming

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

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

    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 callback, it 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 EventEmitter. This 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.domain. But if it has been created earlier and added via add, it 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 add. However, 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.

    Read More:  Bootstrap: TOP 5 Free Bootstrap Editors & Tools

    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?

    Read More:  Deep Learning vs Machine Learning: Overview & Comparison

    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 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
    Medical Marketing August 27, 2025

    Exploring Innovative Content Ideas for Wellness Blogs and Clinics

    In the evolving landscape of wellness, innovative content ideas for blogs and clinics are essential for engagement and patient education. Incorporating multimedia elements, personalized wellness journeys, and evidence-based insights can enhance user experience and foster community.

    21. Уроки Node.js. Writable Поток Ответа res, Метод pipe. Pt.1

    October 25, 2016

    Node.js Lesson 3: Node Package Manager

    September 14, 2020

    Tough Interview

    November 21, 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

    17. Уроки Node.js. Таймеры, Отличия от Браузера, ref и unref

    Programming October 7, 2016

    Handling Side Effects in Redux: Redux-Saga

    JavaScript November 29, 2019

    This Is Why Freelancing Is Not for Everyone | 5 Actual Lessons I Learned as a Freelancer

    Remote Job February 13, 2019

    10 Practices You Should Avoid to Become a Good Java Developer

    Java May 15, 2023

    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
    JavaScript

    Visualizing Logs from a Dockerized Node Application Using the Elastic Stack

    React Native

    Building a Realtime Messaging app with React Native and Firebase

    JavaScript

    Egestas Egestas Fringilla Phasellus Faucibus Scelerisque

    Most Popular

    Why Fastify is a better Nodejs framework for your next project compared to Express

    Node.js

    Enhancing Interview Success: The Critical Role of Confidence

    Interview

    Think Like a Pythonista — Building a Book Sharing App

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

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