Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Minimize Downtime by Creating a Health-check for Your NodeJS Application

    JavaScript

    React Lesson 12: Checking Homework Progress from Lesson 11

    React

    Creating Mock API using Mirage in a React application

    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 / 21. Node.js Lessons. Writable Response Stream (res), Pipe Method. Pt.2
    Programming

    21. Node.js Lessons. Writable Response Stream (res), Pipe Method. Pt.2

    Ivan RastvorovBy Ivan RastvorovOctober 28, 2016Updated:May 26, 2024No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    21. Node.js Lessons. Writable Response Stream (res), Pipe Method. Pt.2
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    lesson21pt2

    Upon the file ending you will see the end event, in the handler of which we will end our response by calling res.end. Thus, the outgoing connection will be closed for the file has been completely sent. The resulting code is quite versatile:

    var http = require('http');
    var fs = require('fs');
    
    new http.Server(function(req, res) {
        // res instanceof http.ServerResponse < stream.Writable
    
        if (req.url == '/big.html') {
    
            var file = new fs.ReadStream('big.html');
            sendFile(file, res);
    
        }
    }).listen(3000);
    
    function sendFile(file, res) {
    
        file.on('readable', write);
    
        function write() {
            var fileContent = file.read(); // read
    
            if (fileContent && !res.write(fileContent)) { // send
    
                file.removeListener('readable', write);
    
                res.once('drain', function() { //wait
                    file.on('readable', write);
                    write();
                });
            }
        }
        file.on('end', function() {
            res.end();
        });
    
    }

    It executes a pretty basic algorithm of sending data from one stream to another by using the most standard methods of the streams readable and writable. Of course, Node.js developers have taken this thing into consideration and added its optimized realization to a standard stream library.

    The respective method is called pipe. See the example:

    var http = require('http');
    var fs = require('fs');
    
    new http.Server(function(req, res) {
        // res instanceof http.ServerResponse < stream.Writable
    
        if (req.url == '/big.html') {
    
            var file = new fs.ReadStream('big.html');
            sendFile(file, res);
    
        }
    }).listen(3000);
    
    function sendFile(file, res) {
    
        file.pipe(res);
    
    }

    All readable streams have it, and it works as follows: readable.pipe (where you write, destination). Moreover, besides it is just one string, there is one more bonus – for example, you can pipe  the same input stream to several output streams:

    function sendFile(file, res) {
    
        file.pipe(res);
        file.pipe(res);
    }

    For example, except for a client response, we will output a standard process output, too:

    file.pipe(res);  
    file.pipe(process.stdout); 
    

    So, we launch it. We see it both in a browser and in a console. Is this code ready for industrial use? Or are there any other aspects we need to consider?

    Read More:  Best Resources for Preparing for Your Technical Interview: Books and Online Platforms

    First, we should pay attention to the fact there is no work on errors and mistakes. If a file is not found or malfunctioning, the whole server will fail. We do not need this scenario. So, let us add this handler:

    function sendFile(file, res) {
    
        file.pipe(res);
    
        file.on('error', function(err) {
            res.statusCode = 500;
            res.end("Server Error");
            console.error(err);
        });
    
    }

    Now we are closer to real life, and some guides consider such code as a good one, but it is not. You may not apply this code to a real-life server. But why? In order to demonstrate the problem let us add some extra handlers to the events open and close for the file.

    function sendFile(file, res) {
    
        file.pipe(res);
    
        file.on('error', function(err) {
            res.statusCode = 500;
            res.end("Server Error");
            console.error(err);
        });
    
        file
            .on('open',function() {
                console.log("open");
            })
            .on('close', function() {
                console.log("close");
            });
    
    }

    Let us launch it. Update the page. Do it several times and look at the console. Notice, the file is getting reset and it is quite normal that the file gets opened. Later it will be fully sent and closed.

    And now let us open the console and launch the utility curl, which will download this url:

    http://localhost:3000/big.html

    with a speed limit of 1KB/sec:

    curl --limit-rate 1k http://localhost:3000/big.html

    If you work under Windows, this utility can be easily found and installed. So, launch it. The file gets opened and downloaded. Everything seems to be ok.

    Push Ctrl+С, end the downloading process. Pay your attention to the fact there is no close . Try it again. It turns out, if a client has opened the connection, but closed it before the download ending, the file stays hung up.

    And if a file stays opened, it means, first, all associated to it structures has remained in the memory; second, operational systems have a limit on the number of simultaneously opened files; third, a respective stream object stays forever in the memory together with the file. And the whole closure, where it is contained.

    Read More:  Web Workers: Concurrency In Java Script

    In order to avoid this problem and its consequences, it will be enough just to catch the moment, when the connection is closed and make sure the file is closed, too.

    The event we are interested in is called  res.on('close'). You won’t find this event in the ordinary stream.Writeable, which means it is exactly the extension of a standard stream interface. Just like files have close, the response object ServerResponse also has close. But the meaning of the latter close cardinally differs from the meaning of the former. It is very important because it is a normal closure (a file gets always closed in the end) for the file stream close, while for the response object close it is a sign the connection has failed. Normal closure doesn’t show close, but  finish. So, if the connections has been broken, we need to close the file and free its resources because we’ve got nobody left to deliver the file to. For that purpose, we call the stream method file.destroy:

    res.on('close', function() {  
      file.destroy();  
    });
    

    Now everything will be all right. Let us check once more. Launch it. So, we can transfer our code to a real-life server.

    You can find the lesson code in our repository.

    1140_pyramids_and_sphinx_of_egypt_556884029e546

    The article materials 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 October 7, 2016

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

    Всем привет! Эта статья посвящена таймерам в Node.js. В ней мы постараемся в первую очередь рассказать о тех различиях, которые есть между таймерами в браузерах и в Node.js.

    23. Уроки Node.js. Домены, “асинхронный try..catch”. Часть 1.

    November 14, 2016

    Nest.js and AWS Lambda for Serverless Microservices

    January 30, 2024

    Essential Skill of Capabilities Assessment

    May 8, 2019

    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

    React Lesson 10: Normalize Data with Immutable.js

    JavaScript March 9, 2020

    Facilisi Nullam Vehicula Ipsum Arcu Cursus Vitae Congue

    Trends January 28, 2020

    React Native vs. Flutter: Which One Would Suit You Better?

    Flutter April 23, 2020

    A/B Testing Explained + a Collection of A/B Testing Learning Resources

    Beginners October 17, 2019

    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

    The Ultimate Guide to Local Lead Generation for Home Service Providers

    Git

    Introduction to GitHub Desktop: A GUI Enhancement to a CLI Approach

    Beginners

    Automating and Scheduling Tasks Using Python

    Most Popular

    Enhancing B2B Lead Generation with Data and Analytics Strategies

    B2B Leads

    Monitoring your NestJS application with Sentry

    JavaScript

    Benchmark Java Applications using JMH

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

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