Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Startups

    Leveraging Crowdfunding to Successfully Fund Your Startup

    SEO & Analytics

    Strategies to Mitigate Duplicate Content in Programmatic SEO

    SEO & Analytics

    Effective Data Visualization Techniques for SEO Reporting

    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 / 13. Уроки Node.js. Разработка, supervisor
    Programming

    13. Уроки Node.js. Разработка, supervisor

    bragin_paBy bragin_paSeptember 21, 2016Updated:May 26, 2024No Comments3 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    13. Уроки Node.js. Разработка, supervisor
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    node-js-development-Brillmindz
    На этом занятии наша основная цель – улучшить нашу разработку на Node.js. Первое средство, которое мы для этого изучим, называется supervisor. До этого момента мы разработали эхо-сервер.

    var http = require('http');
    var url = require('url');
    
    var server = http.createServer();
    
    server.on('request', function(req, res) {
        var urlParsed = url.parse(req.url, true);
    
        if (req.method == 'GET' && urlParsed.pathname == '/echo' && urlParsed.query.message) {
            res.end(urlParsed.query.message );
            return;
        }
    
        res.statusCode = 404;
        res.end('Not Found');
    });
    
    server.listen(1337);

    В процессе разработки была некоторая сложность. Любые изменения в коде требовали перезапуска сервера. Это легко объяснить, ведь Node.js считывает файлы только один раз. Считав файл, он получает соответствующий объект модуля и в дальнейшем использует его. А что делать в процессе разработки?
    Есть, конечно, вариант очистить внутренний cache Node.js, но наиболее часто используют другой подход, а именно специальный модуль, который отслеживает все файлы с директории. Как только в ней что-то меняется, перезапускает Node.js. один из таких модулей называется supervisor. Этот модуль содержит в себе console утилиту, которая должна быть доступна по системному пути.

    Поэтому установим его глобально:
    npm i –g supervisor

    Теперь я запускаю вместо node server.js  -> supervisor server.js

    Что это  нам дает?  Сейчас я изменю файл, например, добавлю в него пустую строку и сохраню то, что получилось.

    var http = require('http');
    var url = require('url');
    
    var server = http.createServer();
    
    server.on('request', function(req, res) {
        var urlParsed = url.parse(req.url, true);
    
        if (req.method == 'GET' && urlParsed.pathname == '/echo' && urlParsed.query.message) {
            res.end(urlParsed.query.message );
            return;
        }
    
    
        res.statusCode = 404;
        res.end('Not Found');
    });
    
    server.listen(1337);

    Вы заметили? Crashing child  и старт новый. Давайте еще раз. Уберем строку, сохраним.

    WebStorm сохраняет при одном нажатии кнопки Save, либо если он теряет фокус. То есть, как только я переключусь на окно браузера, он тут же сохранит  то, что я редактировал.

    Read More:  14. Уроки Node.js. Отладка скриптов. Часть 2.

    Supervisor все время следит за файлами, и как только он видит, что изменились файлы с расширениями по умолчанию node либо js, то перезапускает Node.

    Более того, если в этой директории есть другие файлы, и они изменены, то тоже supervisor смотрит над всем содержимым директории, наблюдает, какие файлы изменились. Как только какой-нибудь из них будет изменен, включая путь директории, то он запустит Node. Это очень удобно при разработке больших многоуровневых проектов.

    Какие подводные камни есть у supervisor? Они тоже присутствуют.
    Первый подводный камень, о котором необходимо знать, это новые файлы. Создадим файл file.js. Сохраним.

    Никакой реакции не происходит. Это потому что supervisor, во всяком случае, текущая его версия, наблюдает за каждым файлом индивидуально. Она просто не знает, что появился новый файл.  Но, если мы после того, как изменили файл, внесем его через require-сервер, то как раз изменения в сервере оно отследит и все перезапустит. Ну, а  после перезапуска будет следить и за новым файлом js тоже. Таким образом, если добавление нового файла влечет за собой изменения существующих, а, как правило, оно так и есть, то у нас все хорошо. Но в тех редких случаях, когда нет, то придется иметь в виду, что нужно перезапускать supervisor вручную. Автоматически новые файлы он не обнаружит.

    Следующий подводный камень supervisor заключается в то, что если мы поставили много модулей, и у нас есть большая директория node.modules, а  каждый модуль ставит свои зависимости, то общее количество файлов в поддиректории может стать очень большим, и supervisor начнет есть очень много процессорного времени. Особенно это заметно на ноутбуках, которые при этом начинают гораздо сильнее греться. Чтобы такого не было, желательно supervisor либо запускать с параметром ignor и указывать в нем что нужно игнорировать  node.modules, либо переместить эту node.modules куда-то наверх, потому что это внешние модули. Они изменяются не так уж часто.

    Read More:  14. Уроки Node.js. Отладка скриптов. Часть 1.

    Итак, далее для разработки мы будем использовать   supervisor.

    Код урока находится в нашем репозитроии.

    weekly-header-boxes-retina

    Материалы взяты из следующего скринкаста

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

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    bragin_pa

      Related Posts

      3. Уроки Express.js. Шаблонизация с EJS: Layout, Block, Partials

      December 16, 2016

      Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 2.

      December 2, 2016

      2. Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 1.

      November 24, 2016
      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 5, 2019

      Essential Tips on How to Become a Full Stack Developer

      This article attempts to answer such questions as ‘are full stack developers even real,’ ‘what are they, these full stack developers,’ and ‘are there any tips on how to become one of those ninjas’?

      Essential Steps to Identify and Validate Your Business Ideas

      November 30, 2024

      Maximizing Efficiency: The Crucial Role of Lean Startup Methodology

      November 26, 2024

      Best Udemy Online Courses to Learn JavaScript, React, Angular, and Node [Only Those Updated in 2019]

      June 4, 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

      Strategies for Identifying Quality LinkedIn Prospects by Niche

      LinkedIn December 7, 2024

      Optimizing LinkedIn Lead Generation: Seamless CRM Integration

      LinkedIn December 7, 2024

      Leveraging Lean Startup Methodology for Business Growth Success

      Startups December 1, 2024

      Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 2.

      Programming December 2, 2016

      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
      Franchising

      A Guide to HR Developing Performance Goals

      Trends

      The Future of Recruitment. Trends, Channels and Tools

      Development

      Strategies for Effectively Managing Software Project Deadlines

      Most Popular

      Introduction to WebAssembly: The Magic of Native Code in Web Apps

      JavaScript

      28 Sample Interview Questions for JavaScript Developers | Theory and Practice

      Interview

      Building a Simple CLI Youtube Video Downloader in NodeJS

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

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