<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Megha D Parmar on Medium]]></title>
        <description><![CDATA[Stories by Megha D Parmar on Medium]]></description>
        <link>https://medium.com/@megha.d.parmar2018?source=rss-e3153e31b6df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cBazIuH9-o5wSZQr</url>
            <title>Stories by Megha D Parmar on Medium</title>
            <link>https://medium.com/@megha.d.parmar2018?source=rss-e3153e31b6df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 00:07:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@megha.d.parmar2018/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Master RxJS operators in Angular: 10 Essential Operators with Real Business Use Cases]]></title>
            <link>https://medium.com/@megha.d.parmar2018/master-rxjs-operators-in-angular-10-essential-operators-with-real-business-use-cases-9d670f1a9848?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d670f1a9848</guid>
            <category><![CDATA[rxjs-pipe]]></category>
            <category><![CDATA[angular-rxjs-operators]]></category>
            <category><![CDATA[angular-observable-pipe]]></category>
            <category><![CDATA[rxjs-operators-in-angular]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 12:16:33 GMT</pubDate>
            <atom:updated>2025-09-30T12:16:33.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czJmuo1cwxfAzFO8T2fRfw.png" /></figure><p>Angular has fully embraced reactive programming as its core paradigm, and with the introduction of Angular 19’s new Resource APIs and enhanced signal integration, understanding RxJS operators in Angular has become more critical than ever. While many developers limit themselves to basic .subscribe() calls, the real power lies in mastering the operators that make applications scalable, performant, and maintainable.</p><p>Modern applications rely heavily on RxJS operators in Angular for handling asynchronous data streams, from HTTP requests to user interactions. The latest Angular 19 features, including the new hybrid reactivity model that combines Signals and Observables, make it essential for developers to understand how these operators work in real business scenarios.</p><p>This comprehensive guide explores the most essential angular rxjs operators that every developer should master, complete with practical business use cases that you’ll encounter in production applications. Each example is updated for Angular 19 and uses the latest RxJS syntax patterns that align with current best practices.</p><h3>Setting Up Your Angular 19 Environment</h3><p>Before diving into the operators, let’s establish the proper foundation. Angular 19 introduces significant improvements to how we handle reactive programming, and the setup reflects these changes.</p><pre>// main.ts - Angular 19 standalone bootstrap<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { provideHttpClient } from &#39;@angular/common/http&#39;;<br>import { AppComponent } from &#39;./app/app.component&#39;;<br><br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideHttpClient(),<br>    // Other providers<br>  ]<br>});</pre><p>The rxjs pipe method and operators are imported directly from the RxJS library, making the import structure cleaner and more tree-shakable:</p><pre>import { <br>  map, switchMap, mergeMap, concatMap, exhaustMap, <br>  debounceTime, distinctUntilChanged, catchError, <br>  retryWhen, delay, take, combineLatest, of, from, fromEvent <br>} from &#39;rxjs&#39;;</pre><h3>1. map() — Transform Data for Business Logic</h3><p>The map() operator transforms data as it flows through your observable stream. In business applications, you frequently need to convert backend DTOs into frontend models or calculate derived values.</p><p>Real Business Scenario: Converting API responses to display-friendly formats</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class OrderService {<br>  private http = inject(HttpClient);<br>  <br>  getOrderSummary(): Observable&lt;OrderSummary[]&gt; {<br>    return this.http.get&lt;OrderResponse[]&gt;(&#39;/api/orders&#39;).pipe(<br>      map(orders =&gt; orders.map(order =&gt; ({<br>        id: order.orderId,<br>        customerName: `${order.customer.firstName} ${order.customer.lastName}`,<br>        totalAmount: order.items.reduce((sum, item) =&gt; sum + (item.price * item.quantity), 0),<br>        status: this.formatOrderStatus(order.status),<br>        estimatedDelivery: new Date(order.createdAt.getTime() + (7 * 24 * 60 * 60 * 1000))<br>      })))<br>    );<br>  }<br>}</pre><p>This transformation happens every time new data arrives, ensuring your UI always receives properly formatted information without cluttering your components with data manipulation logic.</p><h3>2. switchMap() — Handle User Input Efficiently</h3><p>The switchMap() operator cancels previous inner observables when a new value arrives. This behavior makes it perfect for search functionality where you want to cancel outdated requests.</p><p>Real Business Scenario: Product search with automatic cancellation</p><pre>@Component({<br>  selector: &#39;app-product-search&#39;,<br>  template: `<br>    &lt;input #searchInput placeholder=&quot;Search products...&quot; /&gt;<br>    &lt;div *ngFor=&quot;let product of searchResults$ | async&quot;&gt;<br>      {{ product.name }} - ${{ product.price }}<br>    &lt;/div&gt;<br>  `<br>})<br>export class ProductSearchComponent implements OnInit {<br>  private searchInput = viewChild.required&lt;ElementRef&gt;(&#39;searchInput&#39;);<br>  private productService = inject(ProductService);<br>  <br>  searchResults$!: Observable&lt;Product[]&gt;; <br><br>ngOnInit() {<br>    this.searchResults$ = fromEvent(this.searchInput().nativeElement, &#39;input&#39;).pipe(<br>      map((event: any) =&gt; event.target.value),<br>      debounceTime(300),<br>      distinctUntilChanged(),<br>      switchMap(query =&gt; <br>        query.length &gt; 2 <br>          ? this.productService.searchProducts(query)<br>          : of([])<br>      )<br>    );<br>  }<br>}</pre><p>Using rxjs pipe with switchMap ensures that if a user types quickly, only the latest search request matters, preventing race conditions and reducing server load.</p><h3>3. mergeMap() — Process Multiple Requests Simultaneously</h3><p>When you need to handle multiple asynchronous operations in parallel, mergeMap() processes all inner observables concurrently without canceling previous ones.</p><p>Real Business Scenario: Loading customer data with their recent orders simultaneously</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class CustomerDashboardService {<br>  private http = inject(HttpClient);<br>loadCustomerDashboard(customerIds: string[]): Observable&lt;CustomerDashboard&gt; {<br>    return from(customerIds).pipe(<br>      mergeMap(customerId =&gt; <br>        combineLatest([<br>          this.http.get&lt;Customer&gt;(`/api/customers/${customerId}`),<br>          this.http.get&lt;Order[]&gt;(`/api/customers/${customerId}/orders?limit=5`)<br>        ]).pipe(<br>          map(([customer, orders]) =&gt; ({ customer, orders }))<br>        )<br>      ),<br>      // Collect all results<br>      toArray(),<br>      map(results =&gt; ({ dashboards: results, totalCustomers: results.length }))<br>    );<br>  }<br>}</pre><p>This approach maximizes performance by making parallel API calls rather than waiting for each request to complete sequentially.</p><h3>4. concatMap() — Maintain Order in Sequential Operations</h3><p>Unlike mergeMap(), concatMap() processes inner observables one at a time, maintaining the order of operations. This is crucial for business processes that must happen in sequence.</p><p>Real Business Scenario: Processing payment and then updating inventory</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class CheckoutService {<br>  private http = inject(HttpClient);<br>processCheckout(order: Order): Observable&lt;CheckoutResult&gt; {<br>    return of(order).pipe(<br>      concatMap(order =&gt; this.processPayment(order)),<br>      concatMap(paymentResult =&gt; <br>        this.updateInventory(paymentResult.orderId).pipe(<br>          map(inventoryUpdate =&gt; ({ <br>            ...paymentResult, <br>            inventoryUpdated: inventoryUpdate.success <br>          }))<br>        )<br>      ),<br>      concatMap(result =&gt; <br>        this.sendConfirmationEmail(result.customerEmail).pipe(<br>          map(emailResult =&gt; ({ <br>            ...result, <br>            emailSent: emailResult.success <br>          }))<br>        )<br>      )<br>    );<br>  }<br>}</pre><p>Each step waits for the previous one to complete, ensuring business logic integrity throughout the checkout process.</p><h3>5. exhaustMap() — Prevent Duplicate Operations</h3><p>The exhaustMap() operator ignores new values while the current inner observable is still active. This prevents duplicate operations, making it ideal for preventing double-clicks on critical actions.</p><p>Real Business Scenario: Preventing duplicate payment submissions</p><pre>@Component({<br>  selector: &#39;app-payment-form&#39;,<br>  template: `<br>    &lt;button #payButton (click)=&quot;processPayment()&quot; <br>            [disabled]=&quot;isProcessing$ | async&quot;&gt;<br>      {{ (isProcessing$ | async) ? &#39;Processing...&#39; : &#39;Pay Now&#39; }}<br>    &lt;/button&gt;<br>  `<br>})<br>export class PaymentFormComponent {<br>  private paymentService = inject(PaymentService);<br>  private payButton = viewChild.required&lt;ElementRef&gt;(&#39;payButton&#39;);<br>  <br>  isProcessing$ = new BehaviorSubject(false);<br>  <br>  ngOnInit() {<br>    fromEvent(this.payButton().nativeElement, &#39;click&#39;).pipe(<br>      exhaustMap(() =&gt; {<br>        this.isProcessing$.next(true);<br>        return this.paymentService.processPayment(this.paymentData).pipe(<br>          finalize(() =&gt; this.isProcessing$.next(false))<br>        );<br>      })<br>    ).subscribe(result =&gt; {<br>      // Handle successful payment<br>      this.handlePaymentSuccess(result);<br>    });<br>  }<br>}</pre><p>This pattern ensures that even if users frantically click the payment button, only one payment request processes at a time.</p><h3>6. debounceTime() — Optimize User Input Handling</h3><p>The debounceTime() operator delays emissions until a specified time has passed without new values. This is essential for optimizing API calls triggered by user input.</p><p>Real Business Scenario: Auto-saving form data without overwhelming the server</p><pre>@Component({<br>  selector: &#39;app-document-editor&#39;,<br>  template: `<br>    &lt;textarea [(ngModel)]=&quot;documentContent&quot; <br>              (input)=&quot;onContentChange($event)&quot;&gt;<br>    &lt;/textarea&gt;<br>    &lt;div class=&quot;save-status&quot;&gt;{{ saveStatus$ | async }}&lt;/div&gt;<br>  `<br>})<br>export class DocumentEditorComponent implements OnInit {<br>  private documentService = inject(DocumentService);<br>  private contentSubject = new Subject&lt;string&gt;();<br>  <br>  saveStatus$ = new BehaviorSubject&lt;string&gt;(&#39;All changes saved&#39;);<br>  documentContent = &#39;&#39;;<br><br>  ngOnInit() {<br>      this.contentSubject.pipe(<br>        debounceTime(1000), // Wait 1 second after user stops typing<br>        distinctUntilChanged(),<br>        tap(() =&gt; this.saveStatus$.next(&#39;Saving...&#39;)),<br>        switchMap(content =&gt; <br>          this.documentService.saveDocument(this.documentId, content).pipe(<br>            map(() =&gt; &#39;All changes saved&#39;),<br>            catchError(() =&gt; of(&#39;Error saving document&#39;))<br>          )<br>        )<br>      ).subscribe(status =&gt; this.saveStatus$.next(status));<br>    }<br>    onContentChange(event: any) {<br>      this.contentSubject.next(event.target.value);<br>    }<br>}</pre><p>This approach provides a smooth user experience while minimizing server requests and preventing data loss.</p><h3>7. distinctUntilChanged() — Eliminate Redundant Processing</h3><p>This operator only emits values that are different from the previous emission, preventing unnecessary processing and API calls when data hasn’t actually changed.</p><p>Real Business Scenario: Filtering dashboard data without redundant requests</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class DashboardService {<br>  private http = inject(HttpClient);<br>  private filterSubject = new BehaviorSubject&lt;DashboardFilter&gt;({<br>    dateRange: &#39;last30days&#39;,<br>    category: &#39;all&#39;,<br>    status: &#39;active&#39;<br>  });<br><br>dashboardData$ = this.filterSubject.pipe(<br>    distinctUntilChanged((prev, curr) =&gt; <br>      JSON.stringify(prev) === JSON.stringify(curr)<br>    ),<br>    debounceTime(300),<br>    switchMap(filter =&gt; this.loadDashboardData(filter))<br>  );<br>  updateFilter(newFilter: Partial&lt;DashboardFilter&gt;) {<br>    const currentFilter = this.filterSubject.value;<br>    this.filterSubject.next({ ...currentFilter, ...newFilter });<br>  }<br>}</pre><p>Understanding angular rxjs operators like distinctUntilChanged helps prevent unnecessary API calls when filter objects are recreated but contain the same values.</p><h3>8. catchError() — Graceful Error Handling</h3><p>The catchError() operator allows you to handle errors gracefully and provide fallback values or alternative data sources when operations fail.</p><p>Real Business Scenario: Providing fallback data when primary services are unavailable</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class UserProfileService {<br>  private http = inject(HttpClient);<br>getUserProfile(userId: string): Observable&lt;UserProfile&gt; {<br>    return this.http.get&lt;UserProfile&gt;(`/api/users/${userId}/profile`).pipe(<br>      catchError(error =&gt; {<br>        console.error(&#39;Primary profile service failed:&#39;, error);<br>        <br>        // Try backup service<br>        return this.http.get&lt;UserProfile&gt;(`/api/backup/users/${userId}`).pipe(<br>          catchError(backupError =&gt; {<br>            console.error(&#39;Backup service also failed:&#39;, backupError);<br>            <br>            // Return minimal profile from cache or default<br>            return of({<br>              id: userId,<br>              name: &#39;User&#39;,<br>              email: &#39;user@example.com&#39;,<br>              avatar: &#39;/assets/default-avatar.png&#39;,<br>              isFromCache: true<br>            });<br>          })<br>        );<br>      })<br>    );<br>  }<br>}</pre><p>This layered error handling ensures your application remains functional even when services experience issues.</p><h3>9. retryWhen() — Smart Retry Logic</h3><p>The retryWhen() operator provides sophisticated retry mechanisms with custom logic for handling temporary failures.</p><p>Real Business Scenario: Retrying failed API calls with exponential backoff</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class DataSyncService {<br>  private http = inject(HttpClient);<br>  <br>  tsyncCriticalData(): Observable&lt;SyncResult&gt; {<br>    return this.http.post&lt;SyncResult&gt;(&#39;/api/sync&#39;, this.getPendingData()).pipe(<br>      retryWhen(errors =&gt; <br>        errors.pipe(<br>          scan((retryCount, error) =&gt; {<br>            if (retryCount &gt;= 3) {<br>              throw error; // Stop retrying after 3 attempts<br>            }<br>            <br>            // Only retry on network errors or 5xx server errors<br>            if (error.status === 0 || (error.status &gt;= 500 &amp;&amp; error.status &lt; 600)) {<br>              return retryCount + 1;<br>            }<br>            <br>            throw error; // Don&#39;t retry client errors (4xx)<br>          }, 0),<br>          delay(1000), // Wait 1 second before retry<br>          tap(retryCount =&gt; <br>            console.log(`Retrying sync operation, attempt ${retryCount + 1}`)<br>          )<br>        )<br>      ),<br>      catchError(error =&gt; {<br>        // Log final failure and return safe fallback<br>        console.error(&#39;Sync failed after all retries:&#39;, error);<br>        return of({ success: false, error: &#39;Sync temporarily unavailable&#39; });<br>      })<br>    );<br>  }<br>}</pre><p>This intelligent retry logic helps handle temporary network issues while avoiding infinite retry loops on permanent failures.</p><h3>10. combineLatest() — Reactive Dashboard Updates</h3><p>The combineLatest() operator combines multiple observables and emits whenever any of them changes, making it perfect for reactive dashboards that depend on multiple data sources.</p><p>Real Business Scenario: Real-time analytics dashboard with multiple filters</p><pre>@Component({<br>  selector: &#39;app-analytics-dashboard&#39;,<br>  template: `<br>    &lt;div class=&quot;filters&quot;&gt;<br>      &lt;select [(ngModel)]=&quot;selectedRegion&quot;&gt;<br>        &lt;option *ngFor=&quot;let region of regions&quot; [value]=&quot;region&quot;&gt;{{ region }}&lt;/option&gt;<br>      &lt;/select&gt;<br>      &lt;input type=&quot;date&quot; [(ngModel)]=&quot;selectedDate&quot; /&gt;<br>      &lt;select [(ngModel)]=&quot;selectedMetric&quot;&gt;<br>        &lt;option value=&quot;revenue&quot;&gt;Revenue&lt;/option&gt;<br>        &lt;option value=&quot;users&quot;&gt;Active Users&lt;/option&gt;<br>        &lt;option value=&quot;conversions&quot;&gt;Conversions&lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;dashboard&quot; *ngIf=&quot;dashboardData$ | async as data&quot;&gt;<br>      &lt;div class=&quot;metric-card&quot; *ngFor=&quot;let metric of data.metrics&quot;&gt;<br>        {{ metric.name }}: {{ metric.value | currency }}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class AnalyticsDashboardComponent implements OnInit {<br>  private analyticsService = inject(AnalyticsService);<br>  <br>  selectedRegion = &#39;all&#39;;<br>  selectedDate = new Date().toISOString().split(&#39;T&#39;)[0];<br>  selectedMetric = &#39;revenue&#39;;<br>  <br>  regions = [&#39;all&#39;, &#39;north&#39;, &#39;south&#39;, &#39;east&#39;, &#39;west&#39;];<br>  <br>  dashboardData$!: Observable&lt;DashboardData&gt;;<br><br>  ngOnInit() {<br>      const region$ = new BehaviorSubject(this.selectedRegion);<br>      const date$ = new BehaviorSubject(this.selectedDate);<br>      const metric$ = new BehaviorSubject(this.selectedMetric);<br>      this.dashboardData$ = combineLatest([<br>        region$,<br>        date$,<br>        metric$<br>      ]).pipe(<br>        debounceTime(300), // Prevent rapid-fire updates<br>        switchMap(([region, date, metric]) =&gt; <br>          this.analyticsService.getDashboardData({<br>            region,<br>            date,<br>            metric<br>          })<br>        ),<br>        catchError(error =&gt; {<br>          console.error(&#39;Dashboard data loading failed:&#39;, error);<br>          return of({ metrics: [], error: &#39;Unable to load dashboard data&#39; });<br>        })<br>      );<br>      // Update streams when form values change<br>      this.setupFormValueStreams(region$, date$, metric$);<br>    }<br>  }</pre><p>Using angular observable pipe in templates combined with combineLatest creates responsive dashboards that update automatically when any filter changes.</p><h3>Advanced Tips for Production Applications</h3><p>Learning rxjs operators in angular with example implementations is just the beginning. Here are some advanced patterns that separate professional developers from beginners:</p><p>Memory Management: Always use the takeUntil pattern with a destroy subject to prevent memory leaks:</p><pre>export class ComponentWithSubscriptions implements OnInit, OnDestroy {<br>  private destroy$ = new Subject&lt;void&gt;();<br>  <br>  ngOnInit() {<br>    this.dataService.getData().pipe(<br>      takeUntil(this.destroy$)<br>    ).subscribe(data =&gt; {<br>      // Handle data<br>    });<br>  }<br>  ngOnDestroy() {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><p>Error Boundaries: Implement global error handling for better user experience:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class GlobalErrorHandler {<br>  handleError&lt;T&gt;(operation = &#39;operation&#39;, result?: T) {<br>    return (error: any): Observable&lt;T&gt; =&gt; {<br>      console.error(`${operation} failed:`, error);<br>      <br>      // Send error to logging service<br>      this.logError(error);<br>      <br>      // Show user-friendly message<br>      this.notificationService.showError(`${operation} failed. Please try again.`);<br>      <br>      // Return safe fallback<br>      return of(result as T);<br>    };<br>  }<br>}</pre><p>Performance Optimization: Use Angular 19’s new Resource APIs alongside RxJS for optimal performance:</p><pre>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `<br>    @if (usersResource.loading()) {<br>      &lt;div class=&quot;loading&quot;&gt;Loading users...&lt;/div&gt;<br>    } @else if (usersResource.error()) {<br>      &lt;div class=&quot;error&quot;&gt;{{ usersResource.error() }}&lt;/div&gt;<br>    } @else {<br>      @for (user of usersResource.value(); track user.id) {<br>        &lt;div class=&quot;user-card&quot;&gt;{{ user.name }}&lt;/div&gt;<br>      }<br>    }<br>  `<br>})<br>export class UserListComponent {<br>  private http = inject(HttpClient);<br>  <br>  usersResource = resource({<br>    loader: () =&gt; this.http.get&lt;User[]&gt;(&#39;/api/users&#39;).pipe(<br>      map(users =&gt; users.filter(user =&gt; user.active)),<br>      catchError(this.errorHandler.handleError(&#39;load users&#39;, []))<br>    )<br>  });<br>}</pre><h3>Conclusion</h3><p>Mastering RxJS operators in Angular transforms how you build applications. These ten operators provide the foundation for creating scalable, maintainable, and performant applications that handle real business requirements effectively.</p><p>The key to success lies in understanding when to use each operator and how they work together. Start by implementing these patterns in your current projects, focusing on one operator at a time until the concepts become second nature.</p><p>As Angular continues evolving with features like the hybrid reactivity model in Angular 19, combining these RxJS patterns with new APIs like Resources and Signals will keep your applications at the forefront of modern web development. The investment in learning these operators pays dividends in code quality, application performance, and your professional development as an Angular developer.</p><p>Remember that this comprehensive rxjs operators tutorial for angular provides the foundation, but real mastery comes from applying these patterns to solve actual business problems in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d670f1a9848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Angular Development with SCSS: Unleashing the Potential of Sassy CSS]]></title>
            <link>https://medium.com/@megha.d.parmar2018/boosting-angular-development-with-scss-unleashing-the-potential-of-sassy-css-217559d48b0b?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/217559d48b0b</guid>
            <category><![CDATA[angular-sassy-css]]></category>
            <category><![CDATA[scss-angular-architecture]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[sassy-css-architecture]]></category>
            <category><![CDATA[sassy-css]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 13:38:18 GMT</pubDate>
            <atom:updated>2024-09-17T06:41:31.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVyJxDdDBHHDRVdbrI3gyw.jpeg" /></figure><h3><strong>Introduction:</strong></h3><p>In the dynamic world of Angular development, every line of code matters. To streamline your styling workflow and optimize your Angular project, let’s delve into the transformative capabilities of SCSS (Sassy CSS). This comprehensive guide will walk you through the essence of SCSS, highlighting its standout features with practical examples, and demonstrating why SCSS is a game-changer for Angular projects. From seamless integration to leveraging functions for enhanced styling, we’ll cover it all.</p><h4><strong>What is SCSS?</strong></h4><p>SCSS is the evolution of CSS, offering an array of features to elevate your styling experience. With variables, nesting, mixins, inheritance, and functions, SCSS empowers Angular developers to craft cleaner, more maintainable stylesheets that align perfectly with the Angular framework.</p><h4>Key Features of SCSS with Examples:</h4><p><strong>(1) Variables</strong>: Enhance consistency and facilitate updates with reusable values.</p><pre>/* _variable.scss */<br><br>$primary-color: #007bff;<br>$secondary-color: #6c757d;<br>$default-color: #f77f3f;<br><br>$btn-background: #d04a02;<br>$btn-border: #185abd;<br>$text-color-white: #ffffff;</pre><p><strong>(2) Nesting</strong>: Improve readability and structure by nesting CSS selectors.</p><pre>.base-button {<br>    background-color: $default-color;<br>}</pre><p><strong>(3) Mixins</strong>: Simplify styling and promote code reuse with reusable blocks of styles.</p><pre>/* _mixin.scss */<br>@mixin button {<br>  background-color: $btn-background;<br>  color: $text-color-white;<br>  border-color: $btn-border;<br>  font-weight: 500;<br>  font-size: large;<br>  border-radius: 5px;<br>  border: none;<br>}</pre><p><strong>(4) Inheritance</strong>: Streamline your stylesheet by extending a base style into other selectors.</p><pre>/* _button.scss */<br>.base-button {<br>  padding: 10px 20px;<br>}<br><br>.primary-button {<br>  @extend .base-button;<br>  background-color: $primary-color;<br>  color: white;<br>}</pre><p><strong>(5) Functions</strong>: Create dynamic stylesheets with custom functions.</p><pre>/* _functions.scss */<br>@function em($pixels, $base-font-size: 16px) {<br>  @return ($pixels / $base-font-size) + 0em;<br>}<br><br>.container {<br>  font-size: em(16px); // Converts 16px to em units<br>}</pre><h4><strong>Why SCSS for Angular?</strong></h4><blockquote>Integrating SCSS into your Angular project offers numerous advantages:</blockquote><blockquote><strong>Component-Based Styling</strong>: SCSS aligns seamlessly with Angular’s component-based architecture, enabling more modular and maintainable styling.</blockquote><blockquote><strong>Enhanced Readability and Maintainability</strong>: SCSS’s intuitive syntax and features enhance code readability and simplify maintenance, saving valuable development time.</blockquote><blockquote><strong>Optimized Performance</strong>: SCSS’s efficient compilation and dynamic features contribute to faster load times and better performance, essential for Angular projects.</blockquote><blockquote><strong>Overcoming CSS Challenges:</strong></blockquote><blockquote><strong>Code Repetition</strong>: SCSS’s mixins and inheritance features minimize redundancy, making it easier to reuse styles efficiently and maintain code.</blockquote><blockquote><strong>Global Scope</strong>: SCSS’s modular approach, combined with Angular’s component-based architecture, isolates styles within components, preventing unintended style conflicts.</blockquote><blockquote><strong>Complexity</strong>: SCSS’s features like nesting and variables simplify stylesheet organization and maintenance, even as web applications grow in size and complexity.</blockquote><h4>When to Use Inheritance, Mixins, and Functions:</h4><ul><li><strong>Inheritance</strong>: Extend a base style into other selectors across your Angular components for consistent styling and code reuse.</li><li><strong>Mixins</strong>: Abstract and reuse groups of properties across multiple selectors within your Angular project.</li><li><strong>Functions</strong>: Create dynamic stylesheets and perform custom calculations or conversions.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-kl8kpv%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-kl8kpv&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-kl8kpv%2Ff317f0d66b9cd1d48080b4037a9463a3&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/edd03262f0ad9396bc057a83ea812ed3/href">https://medium.com/media/edd03262f0ad9396bc057a83ea812ed3/href</a></iframe><h4>Explanation:</h4><p>The <strong>_variable.scss</strong> file in an Angular project is used to centralize and define reusable style variables like colors and button styles in Sass syntax. This approach encourages consistency in styling throughout the project while making maintenance easier by allowing for instant modifications across various components.</p><p>The <strong>_mixin.scss</strong> file creates a reusable mixin named button, which contains style directives for creating uniform button designs throughout an Angular project. This ensures consistency in button styling and streamlines the process of applying these styles throughout the project.</p><p>The purpose of the <strong>_function.scss</strong> file is to define a Sass function called em. This function converts pixel data into em units, which helps developers build versatile and adaptable layouts in Angular projects.</p><p>The <strong>_buttons.scss</strong> file is used to centralize the styling of buttons in an Angular project. Importing variables, mixins, and functions provides consistency and ease of use. The stated styles, which include base button padding and button variations, enable efficient and consistent button design across the project.</p><h4>Conclusion:</h4><p>Transform your Angular project with the power of SCSS. By leveraging its robust features, including variables, nesting, mixins, inheritance, and functions, you can create cleaner, more efficient stylesheets that seamlessly integrate with Angular’s architecture, enhancing readability, maintainability, and performance.</p><blockquote>Promoting iFour Technolab like it is a leading IT firm that offers best angular development services, etc etc.<br>If you are need for assistance, then partner with iFour, a leading Angular development company <a href="https://www.ifourtechnolab.com/">https://www.ifourtechnolab.com/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=217559d48b0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Streamlined Validation and Error Management with Joi and express-validator]]></title>
            <link>https://medium.com/@megha.d.parmar2018/a-guide-to-streamlined-validation-and-error-management-with-joi-and-express-validator-98430fda0f5c?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/98430fda0f5c</guid>
            <category><![CDATA[handler]]></category>
            <category><![CDATA[error-response-handler]]></category>
            <category><![CDATA[joi]]></category>
            <category><![CDATA[validator-node]]></category>
            <category><![CDATA[express-validator]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 05:35:41 GMT</pubDate>
            <atom:updated>2023-08-23T06:07:27.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*u83lnDxjGg26Kb2HZ2YQ1A.png" /></figure><h3>Introduction:</h3><p>Node.js applications often deal with data validation and error management to ensure the reliability and security of user input. In this guide, we will walk through an easy and simple approach to perform add validation using the Joi library and effectively manage errors in your Node.js application.</p><p>Joi is a versatile validation library for data validation. It’s not tied to Express and can be used in any JavaScript environment. It’s great for validating complex data structures and ensuring data integrity.</p><h3>Prerequisites:</h3><ul><li>Basic understanding of Node.js and JavaScript</li><li>Familiarity with npm and package.json</li></ul><p><strong>Step 1</strong>: Project Setup: Start by creating a new Node.js project and installing the necessary packages.</p><ol><li>Create a new project directory and navigate to it.</li><li>Run npm init to initialize your project and create a package.json.</li></ol><p><strong>Step 2</strong>: Installing Dependencies: Install the joi library for data validation and the create responseHandler.js file for handling response.</p><ol><li>Install the packages using the following command:</li></ol><pre>npm install joi</pre><pre>// responseHandler.js<br><br>const apiResponse = (res, statusCode, message, data = [], error = []) =&gt; {<br>const resp = data &amp;&amp; data.data<br>      ? { statusCode, message, ...data, error }<br>      : { statusCode, message, data, error };<br><br>return res.status(statusCode).send(resp);<br>};<br><br>module.exports = apiResponse;</pre><p><strong>Step 3</strong>: Let&#39;s dive into the actual implementation of add validation using Joi and effective error/response management.</p><ol><li>In your project directory, create a new JavaScript file (e.g., index.js).</li><li>Import the required modules:</li></ol><pre>const Joi = require(&#39;joi&#39;); </pre><p>Create user-joi.validator.js file for define an add validation schema using Joi:</p><pre>const nameMessages = {<br>  &quot;string.base&quot;: &quot;Name must be a string&quot;,<br>  &quot;string.empty&quot;: &quot;Name is required&quot;,<br>  &quot;string.min&quot;: &quot;Name must be at least {#limit} characters&quot;,<br>  &quot;string.max&quot;: &quot;Name must not exceed {#limit} characters&quot;,<br>  &quot;any.required&quot;: &quot;Name is required&quot;,<br>};<br><br>const emailMessages = {<br>  &quot;string.base&quot;: &quot;Email must be a string&quot;,<br>  &quot;string.empty&quot;: &quot;Email is required&quot;,<br>  &quot;string.email&quot;: &quot;Invalid email format&quot;,<br>  &quot;any.required&quot;: &quot;Email is required&quot;,<br>};<br><br>const ageMessages = {<br>  &quot;number.base&quot;: &quot;Age must be a number&quot;,<br>  &quot;number.empty&quot;: &quot;Age is required&quot;,<br>  &quot;number.integer&quot;: &quot;Age must be an integer&quot;,<br>  &quot;number.min&quot;: &quot;Age must be at least {#limit}&quot;,<br>  &quot;number.max&quot;: &quot;Age must not exceed {#limit}&quot;,<br>};<br><br>const schema = Joi.object({<br>  name: Joi.string().required().messages(nameMessages),<br>  email: Joi.string().email().required().messages(emailMessages),<br>  age: Joi.number().min(18).max(100).required().messages(ageMessages),<br>});</pre><p>Validate req.body with defined schema</p><pre>const { error, value } = schema.validate(req.body, options);<br><br>  if (error) {<br>    apiResponse(res, ERROR_CODE, errors.array()[0], [], errors.array());<br>  } else {<br>    next();<br>  }</pre><p>Use validation with post method. validateUser function will excute before createUser function</p><pre>const router = express.Router();<br>const userValidation = require(&quot;../validator/user-joi.validator&quot;);<br>const userController = require(&quot;../controller/user.controller&quot;);<br><br>router.post(<br>  &quot;/user&quot;, <br>  userValidation.validateUser, <br>  userController.createUser<br>  );<br><br>module.exports = router;</pre><p><strong>Step 4</strong>: Running the Application: Start your Node.js application to see validation and error/response management in action.</p><ol><li>In the terminal, run the following command:</li></ol><pre>node index.js</pre><p>Here are some of the joi functions which we used to validate property.</p><p><strong>1. Joi.string():</strong> It validates that all properties are string<br><strong>2. Joi.alphanum():</strong> It must contain only alphanumeric characters.<br><strong>3. Joi.min():</strong> It specifies the minimum number.<br><strong>4. Joi.max():</strong> It specifies the maximum number.<br><strong>5. Joi.trim():</strong> Requires the string value to contain no whitespace before or after.<br><strong>6. Joi.required():</strong> Make a property required which will not allow undefined as value.<br><strong>7. </strong><a href="http://joi.email/"><strong>Joi.email</strong></a><strong>():</strong> It validates that the email property contains a valid email address.<br><strong>8. Joi.length():</strong> It specifies the exact number of character or number of items in the array.<br><strong>9. Joi.pattern():</strong> A pattern will be a regular expression. It specifies validation rules for matching a pattern.<br><strong>10. Joi.integer():</strong> Requires the number to be an integer (no floating point).<strong><br>11. Joi.array(): Generates a schema object that matches an array data type.<br>12. Joi.items(): Lists the types allowed for the array values were types — one or more joi schema objects to validate each array item against.<br>13. Joi.default(): creates a default value for property.<br>14. Joi.boolean(): Generates a schema object that matches a boolean data type (as well as the strings ‘true’, ‘false’, ‘yes’, and ‘no’).</strong></p><h3><strong>express-validator</strong>:</h3><p>express-validator is a middleware library designed specifically for use with Express.js. It’s focused on validating and sanitizing data from HTTP requests. It’s a good choice when you want to validate request parameters, query strings, and body data in a web context.</p><p>Install the express-validator packages using the following command:</p><pre>npm install express-validator</pre><p>Import the required modules:</p><pre>const { body, validationResult } = require(&quot;express-validator&quot;);</pre><p>Create user.validator.js file for define an add validation schema using Joi:</p><pre>const { body, validationResult } = require(&quot;express-validator&quot;);<br>const apiResponse = require(&quot;../middlewares/responseHandler&quot;);<br><br>const validateRequestBody = [<br>  body(&quot;name&quot;)<br>    .notEmpty()<br>    .withMessage(&quot;Name is required&quot;)<br>    .isString()<br>    .withMessage(&quot;Name must be a string&quot;)<br>    .isLength({ min: 3 })<br>    .withMessage(&quot;Name must be at least 3 characters&quot;)<br>    .isLength({ max: 100 })<br>    .withMessage(&quot;Name must not exceed 100 characters&quot;)<br>    .trim(),<br>  body(&quot;email&quot;)<br>    .notEmpty()<br>    .withMessage(&quot;Email is required&quot;)<br>    .isString()<br>    .withMessage(&quot;Email must be a string&quot;)<br>    .isEmail()<br>    .withMessage(&quot;Invalid email format&quot;)<br>    .trim(),<br>  body(&quot;age&quot;)<br>    .notEmpty()<br>    .withMessage(&quot;Age is required&quot;)<br>    .isNumeric()<br>    .withMessage(&quot;Age must be a number&quot;)<br>    .isInt()<br>    .withMessage(&quot;Age must be an integer&quot;)<br>    .isFloat({ min: 18, max: 100 })<br>    .withMessage(&quot;Age must be between 18 and 100&quot;)<br>    .toInt(), // Convert the age to an integer<br>];<br><br><br>function validateUser(req, res, next) {<br>  const errors = validationResult(req);<br>  if (errors.array().length &gt; 0) {<br>    // If there are validation errors, send a response with the errors<br>    apiResponse(res, ERROR_CODE, errors.array()[0].msg, [], errors.array());<br>  } else {<br>    next();<br>  }<br>}<br><br>module.exports = { validateUser, validateUserSchema };</pre><p>Use validation with post method. first execute validateUserSchema then will execute validateUser function and last will execute createUser function</p><pre>const router = express.Router();<br>const userValidation = require(&quot;../validator/user.validator&quot;);<br>const userController = require(&quot;../controller/user.controller&quot;);<br><br>router.post(<br>  &quot;/user&quot;,<br>  userValidation.validateUserSchema,<br>  userValidation.validateUser,<br>  userController.createUser<br>);<br><br>module.exports = router;</pre><h3><em>Joi VS. express-validator:</em></h3><p>For request validation in an Express.js application, “express-validator” is a commonly used package due to its integration with Express and its focus on web-related validation tasks. However, if you need more sophisticated validation for various data structures, “joi” might be a better fit. Always consider your specific requirements and preferences when choosing a validation package.</p><h3>References:</h3><ul><li><a href="https://joi.dev/api/?v=17.9.1#example">joi.dev</a></li><li><a href="https://express-validator.github.io/docs/">express-validator | express-validator</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98430fda0f5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring req, res Mechanics in Node.js]]></title>
            <link>https://medium.com/@megha.d.parmar2018/exploring-req-res-mechanics-in-node-js-5b445419d024?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b445419d024</guid>
            <category><![CDATA[req]]></category>
            <category><![CDATA[resp]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 03:36:30 GMT</pubDate>
            <atom:updated>2023-07-25T03:36:30.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction:</h4><p>In Node.js, req, and res callbacks are essential components for handling incoming requests and sending responses to clients. These callbacks allow developers to interact with request data and construct the appropriate server responses.</p><p><strong>req (Request Callback):</strong></p><ul><li>The req callback represents the incoming request from the client.</li><li>It contains information about the client’s request, such as the URL, headers, and any data sent in the request.</li><li>Developers use this callback to understand what the client wants and process the request accordingly.</li></ul><p><strong>res (Response Callback)</strong>:</p><ul><li>The res callback is used to construct and send the response back to the client.</li><li>Developers can set response headers, status codes, and send the content of the response, like HTML or JSON data, using this callback.</li><li>The res callback also enables developers to redirect clients to other URLs or render specific views.</li></ul><p><strong>Methods for the </strong><strong>req (Request) Object:</strong></p><ol><li>req.url: Returns the URL of the incoming request.</li><li>req.method: Returns the HTTP method used by the client (e.g., GET, POST, etc.).</li><li>req.headers: Returns an object containing the headers of the request.</li><li>req.params: Returns an object containing route parameters from the URL.</li><li>req.query: Returns an object containing the query parameters from the URL (for GET requests).</li><li>req.body: Returns the data sent by the client (for POST, PUT, and PATCH requests).</li><li>req.cookies: Returns an object containing the cookies sent by the client.</li><li>req.get(headerName): Returns the value of a specific header in the request.</li><li>req.is(type): Checks if the request&#39;s content type matches the specified MIME type.</li></ol><p><strong>Methods for the </strong><strong>res (Response) Object:</strong></p><ol><li>res.setHeader(headerName, headerValue): Sets a single response header.</li><li>res.writeHead(statusCode, [headers]): Sets the response status code and headers together.</li><li>res.status(statusCode): Sets the HTTP status code of the response.</li><li>res.send(data): Sends the response data to the client. It automatically sets the appropriate Content-Type header based on the data type.</li><li>res.json(data): Sends a JSON response to the client.</li><li>res.redirect(statusCode, path): Redirects the client to the specified path.</li><li>res.sendFile(path, [options], [callback]): Sends a file as the response.</li><li>res.render(view, [locals], callback): Renders a view template and sends it as the response.</li><li>res.cookie(name, value, [options]): Sets a cookie in the response.</li><li>res.clearCookie(name, [options]): Clears a previously set cookie.</li><li>res.end([data]): Ends the response process. Optionally, data can be sent as the last chunk.</li></ol><p>References:</p><p><a href="https://nodejs.org/api/http.html">https://nodejs.org/api/http.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b445419d024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Databases in nodejs]]></title>
            <link>https://medium.com/@megha.d.parmar2018/working-with-databases-in-nodejs-4f981ed63253?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f981ed63253</guid>
            <category><![CDATA[working-with-db-in-nodejs]]></category>
            <category><![CDATA[mongoose-crud]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 08:22:44 GMT</pubDate>
            <atom:updated>2023-07-18T08:22:44.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bu-aK9J-XYyfgCCp" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Comprehensive Guide to Database Integration in Node.js</p><h4><strong>Introduction to databases and database systems:</strong></h4><p><strong><em>Databases</em></strong> are organized collections of data that store and manage information efficiently. They provide a structured way to store and retrieve data, ensuring data integrity and security. Databases play a vital role in various applications, enabling easy access, manipulation, and analysis of data.</p><p>Key Concepts:</p><ul><li>Data: It refers to the information stored in a database, such as customer details, product inventory, or financial records.</li><li>Data Models: Data models define the structure and relationships of the data within a database, ensuring consistency and integrity.</li><li>Tables: In most databases, data is organized into tables, which consist of rows (records) and columns (attributes) that represent specific data entities and their properties.</li><li>Queries: Queries are used to retrieve specific information from the database based on defined criteria. They enable users to search, filter, and analyze data effectively.</li></ul><p>A <strong><em>database system</em></strong> is a software application that allows users to store, manage, and retrieve data effectively. It provides a structured environment to organize data, enabling efficient access and manipulation. A database system consists of a database management system (DBMS), which is the core software responsible for handling database operations, and the database itself, which is the collection of structured data.</p><p>Key Concepts of Database Systems:</p><ol><li>Data Models: Database systems use data models to define the structure and relationships of data within the database. Common data models include relational, hierarchical, network, and object-oriented models.</li><li>Tables and Relationships: In a relational database, data is organized into tables consisting of rows (records) and columns (attributes). Relationships between tables establish connections, allowing data to be linked and accessed across different tables.</li><li>Querying: Querying allows users to retrieve specific information from the database using queries. Queries specify criteria to filter and search for relevant data, enabling powerful data retrieval capabilities.</li><li>Data Integrity: Database systems enforce integrity rules to maintain the accuracy and consistency of data. These rules ensure that data meets specified constraints, preventing the entry of invalid or inconsistent information.</li></ol><h4>Connect to database using mongoose</h4><ol><li>Install Mongoose: Start by installing the Mongoose package from npm. Open your terminal and run the following command:</li></ol><pre>npm install mongoose</pre><ol><li>Import Mongoose: In your Node.js application, import the Mongoose module using the require statement:</li></ol><pre>const mongoose = require(&#39;mongoose&#39;);</pre><ol><li>Connect to the Database: Use the mongoose.connect() method to establish a connection to your MongoDB database. Replace &lt;db_url&gt; with the URL of your MongoDB database. For example:</li></ol><pre>mongoose.connect(&#39;&lt;db_url&gt;&#39;, { useNewUrlParser: true, useUnifiedTopology: true })<br>  .then(() =&gt; {<br>    console.log(&#39;Connected to the database&#39;);<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&#39;Error connecting to the database:&#39;, error);<br>  });</pre><p>Ensure you replace &lt;db_url&gt; with the actual URL of your MongoDB database. The { useNewUrlParser: true, useUnifiedTopology: true } options are recommended to ensure proper connection and compatibility.</p><p>The error event is triggered if there is an error during the connection, and the open event is triggered when the connection is successfully established.</p><h4>CRUD operations with MongoDB:</h4><p>Define a Schema: Start by defining a schema that represents the structure of your MongoDB documents. A schema defines the fields, types, and validation rules for the data. Here’s an example of a simple user schema:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const userSchema = new mongoose.Schema({<br>  name: {<br>    require: true,<br>    type: String,<br>  },<br>  email: {<br>    require: true,<br>    type: String,<br>  },<br>  age: {<br>    require: true,<br>    type: Number,<br>  },<br>});<br>const model = mongoose.model(&quot;User&quot;, userSchema);</pre><p>Create a Document: To create a new document, instantiate a model based on the schema and save it to the database. Here’s an example:</p><pre>async function createUser(req, res) {<br>  const data = new Model({<br>    name: req.body.name,<br>    age: req.body.age,<br>    email: req.body.email,<br>  });<br>  try {<br>    const dataToSave = await data.save();<br>    res<br>      .status(200)<br>      .json(<br>        new BaseResponse().createSuccessResponse(<br>          200,<br>          dataToSave,<br>          &quot;user created&quot;<br>        )<br>      );<br>    // res.status(200).json(dataToSave);<br>  } catch (error) {<br>    res.status(400).json({ message: error.message });<br>  }<br>}</pre><p>Read Documents: To retrieve documents from the database, you can use methods like find(), findOne(), or query helpers provided by Mongoose. Here&#39;s an example using find():</p><pre>async function getUser(req, res) {<br>  try {<br>    const data = await Model.find({ _id: req.params.id });<br>    res.json(data);<br>  } catch (error) {<br>    res.status(500).json({ message: error.message });<br>  }<br>}</pre><p>Update a Document: To update a document, you can use methods like updateOne(), updateMany(), or findOneAndUpdate(). Here&#39;s an example using findOneAndUpdate():</p><pre>async function updateUser(req, res) {<br>  try {<br>    const data = await Model.findOneAndUpdate(<br>      { _id: req.params.id }, // Condition to find the document to update<br>      { ...req.body }, // New values to update<br>      { new: true } // Set to true to return the modified document as the result<br>    res.json(data);<br><br>  } catch (error) {<br>    res.status(500).json({ message: error.message });<br>  }<br>}</pre><p>Delete a Document: To delete a document, you can use methods like deleteOne() or deleteMany(). Here&#39;s an example using deleteOne():</p><pre>async function deleteUser(req, res) {<br>  try {<br>    const id = req.params.id;<br>    const data = await Model.findByIdAndDelete(id);<br>    res.send(`Document with ${data.name} has been deleted..`);<br>  } catch (error) {<br>    res.status(400).json({ message: error.message });<br>  }<br>}</pre><h4>Database Queries and Indexing:</h4><p>Efficient database operations are crucial for modern applications. To optimize performance, harnessing the power of database queries and indexing is essential. In this article, we explore key strategies for leveraging queries and indexing to enhance the speed and efficiency of your database operations.</p><p>Queries: Unveiling the Right Data</p><ul><li>Filter data using query operators ($eq, $ne, $gt, $lt, $in).</li><li>Project only necessary fields to reduce data transfer.</li><li>Sort query results for desired ordering.</li><li>Implement limit and skip for pagination and result set control.</li></ul><p>Indexing: Accelerating Data Access</p><ul><li>Create single-field indexes for frequently queried fields.</li><li>Utilize compound indexes for queries involving multiple fields.</li><li>Employ unique indexes for fields with unique values.</li><li>Optimize and maintain indexes to ensure ongoing performance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f981ed63253" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular unit testing with Jest 2023]]></title>
            <link>https://medium.com/@megha.d.parmar2018/angular-unit-testing-with-jest-2023-2676faa2e564?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/2676faa2e564</guid>
            <category><![CDATA[angular-with-jest-2023]]></category>
            <category><![CDATA[jest-configuration]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[angular-with-jest]]></category>
            <category><![CDATA[jest-config-angular-16]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 12:51:44 GMT</pubDate>
            <atom:updated>2024-02-13T11:01:22.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KTir4y0yD0_4ojRJ.png" /></figure><h3>Introduction</h3><p>In Angular 16, Karma has been deprecated while Jest has been introduced in experimental mode. This means that the Angular team is moving towards Jest as the recommended testing framework for Angular applications. While Karma has been the default testing framework for Angular in the past, Jest is being explored as a potential replacement due to its simplicity, speed, and built-in features like snapshot testing and mocking. However, it’s important to note that Jest is still in the experimental stage in Angular 16, and using it in production may have limitations or unsupported features. Developers should stay informed about the latest updates and recommendations from the Angular team regarding testing frameworks in Angular 16.In this article, we will explore how to add Jest as the testing framework in Angular 16</p><h3>Jest:</h3><p>Jest is a popular testing framework from Facebook, widely used in the React ecosystem. It provides everything needed for unit testing JavaScript applications, including powerful mocking, built-in assertions, code coverage, and headless testing with JSDOM. With a better developer experience and faster execution compared to Karma and Jasmine, Jest is a comprehensive toolkit for unit testing in JavaScript.</p><p>Jest, a testing framework from Facebook, offers several powerful features:</p><ol><li>Powerful mocking capabilities: Jest provides built-in mocking functionalities that allow you to easily create mock implementations of dependencies. This enables you to simulate different scenarios and isolate units of code for effective testing.</li><li>Built-in assertion library: Jest comes with its own assertion library, eliminating the need for additional assertion libraries. It provides a wide range of matchers and assertion methods to ensure your code behaves as expected.</li><li>Built-in code coverage generator: Jest has a built-in code coverage tool that generates reports to show the percentage of code covered by your tests. This helps identify areas of your codebase that may require additional testing.</li><li>JSDOM for headless testing: Jest leverages JSDOM, a library that simulates the browser’s DOM environment. This enables you to run your tests in a headless manner, without the need for a browser or extra configuration. It simplifies running tests on CI servers and ensures consistent test execution.</li></ol><p>I prefer Jest over Karma and Jasmine because I think Jest provides a better developer experience.</p><ol><li>Jest is faster than Karma, offering optimized test execution that reduces testing time and provides quicker feedback during development.</li><li>Jest is well-documented, providing extensive resources and examples that make it easy for developers to get started and effectively use the framework.</li><li>Jest is smarter than Karma as it reruns only affected tests, detecting changes in code and selectively executing relevant tests, improving overall test execution efficiency.</li><li>Jest is a complete toolkit for unit testing, providing powerful mocking capabilities, built-in assertions, code coverage generation, and additional features that streamline the testing process.</li><li>Jest is headless by default with JSDOM, allowing tests to run without the need for a browser, making it suitable for headless testing scenarios and facilitating integration with CI/CD pipelines.</li></ol><h3>Jest setup in an Angular project</h3><h4>Step 1: Create new project by using this command:</h4><pre>ng new angular-jest-demo</pre><h4>Step 2: Uninstall all karma jasmin packages by using below command:</h4><pre>npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter @types/jasmine jasmine-core</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*cp3fCH-ZYoUeA0iRMCUreA.png" /></figure><h4>Step 3: Remove test object from angular.json file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtdAh8pcH-VtqTcbvqhP7Q.png" /></figure><h4>Step 4: Install below mentioned packages:</h4><pre>npm i --save-dev jest @types/jest  jest-preset-angular</pre><p>The @types/jest package provides type declaration files for Jest, enabling TypeScript to perform type checking and provide IntelliSense support for Jest-specific APIs, functions, and matchers.</p><p>The jest-preset-angular package is a crucial tool for running Angular unit tests with Jest. It provides the following features:</p><ol><li>ts-jest: A library included in @types/jest that allows Jest to transpile TypeScript code in-memory, facilitating seamless integration between TypeScript and Jest during testing.</li><li>Snapshot serializers: @types/jest provides specialized serializers for Angular components, enhancing snapshot testing capabilities by enabling easy comparison and validation of component snapshots.</li><li>AST transformers: The included AST transformers in @types/jest modify Angular component code during testing, removing CSS styles and inlining HTML templates. This ensures compatibility with JSDOM, enabling headless testing without relying on external resources.</li></ol><h4>step 5 : Create setup-jest.ts file in root folder</h4><pre>import &#39;jest-preset-angular/setup-jest&#39;;</pre><h4>step 6 : To create jest.config file use below command:</h4><p>npx jest — init</p><p>The npx jest - init command initializes Jest in your project by creating a jest.config.js / jest.config.ts file and providing a guided setup process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*XMEGJ7blIAT64y3Eu2i2vQ.png" /></figure><p>Set preset and setupFilesAfterEnv value in jest.config.ts file which are mentioned on below:</p><pre>preset: &#39;jest-preset-angular&#39;,<br>setupFilesAfterEnv: [&#39;&lt;rootDir&gt;/setup-jest.ts&#39;],</pre><p>We are require to install ts-node for the TypeScript configuration files</p><p><em>npm i ts-node</em></p><p>ts-node is provides a convenient way to execute TypeScript files and experiment with TypeScript code interactively.</p><h4>Step 7 : Update tsconfig.spec.json file</h4><pre>/* To learn more about this file see: https://angular.io/config/tsconfig. */<br>{<br>  &quot;extends&quot;: &quot;./tsconfig.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./out-tsc/spec&quot;,<br>    &quot;types&quot;: [<br>      &quot;jest&quot; // 1<br>    ],<br>    &quot;esModuleInterop&quot;: true, // 2<br>    &quot;emitDecoratorMetadata&quot;: true // 3<br>  },<br>  &quot;include&quot;: [<br>    &quot;src/**/*.spec.ts&quot;,<br>    &quot;src/**/*.d.ts&quot;<br>  ]<br>}</pre><ol><li>Register Jest’s type definitions files with the TypeScript compiler.</li><li>Enable the esModuleInterop option of the TypeScript compiler otherwise Jest will output a lot of warnings in the console.</li><li>Enable the emitDecoratorMetadata option of the TypeScript compiler otherwise Angular&#39;s Dependency Injection won&#39;t work with Jest.</li></ol><h4>step 8: Add jest configuration on package.json inside script tag</h4><pre>    &quot;test&quot;: &quot;jest --verbose&quot;,<br>    &quot;test:coverage&quot;: &quot;jest --coverage&quot;,<br>    &quot;test:watch&quot;: &quot;jest --watch&quot;</pre><h4>Step 9: Write a unit test cases</h4><pre>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>describe(&#39;AppComponent&#39;, () =&gt; {<br>  let component: AppComponent;<br>  let fixture: ComponentFixture&lt;AppComponent&gt;;<br><br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      declarations: [AppComponent],<br>    }).compileComponents();<br>  });<br><br>  beforeEach(() =&gt; {<br>    fixture = TestBed.createComponent(AppComponent);<br>    component = fixture.componentInstance;<br>    fixture.detectChanges();<br>  });<br><br>  it(&#39;should create the app&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br><br>  it(`should have as title &#39;demo-angular-jest&#39;`, () =&gt; {<br>    expect(component.title).toEqual(&#39;demo-angular-jest&#39;);<br>  });<br><br>  it(&#39;should render the title&#39;, () =&gt; {<br>    const compiled = fixture.nativeElement as HTMLElement;<br>    expect(compiled.querySelector(&#39;.content span&#39;)?.textContent).toContain(&#39;demo-angular-jest app is running!&#39;);<br>  });<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjuL0H23ceAdMEhtYsEZaA.png" /></figure><h3>References:</h3><p><a href="https://github.com/Megha-Parmar/angular-jest-demo/commit/03543076f867186441465d8d8bbade67587919f3">https://github.com/Megha-Parmar/angular-jest-demo/commit/03543076f867186441465d8d8bbade67587919f3</a></p><ul><li><a href="https://www.xfive.co/blog/testing-angular-faster-jest/">Testing Angular Faster with Jest - Xfive</a></li><li><a href="https://allenhwkim.medium.com/angular5-jest-unit-test-examples-a9538ece6cd">Angular5+ Jest Unit Test Examples</a></li></ul><p><a href="https://dev.to/dstrekelj/how-to-write-unit-tests-in-javascript-with-jest-2e83">https://dev.to/dstrekelj/how-to-write-unit-tests-in-javascript-with-jest-2e83</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2676faa2e564" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 16 Features]]></title>
            <link>https://medium.com/@megha.d.parmar2018/angular-16-features-ac99edc02c20?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac99edc02c20</guid>
            <category><![CDATA[angular-16-features]]></category>
            <category><![CDATA[angular-16]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 12:58:56 GMT</pubDate>
            <atom:updated>2023-07-27T08:56:50.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*FyGEM8fGydIpGUSLjeNSqw.png" /></figure><p>Angular v16 has released in May 2023; in this article, we will discuss new features introduced in angular v16 has been released with some new features and enhancements.</p><h3>Angular Signal</h3><p>The Signal pattern has been present in the Solid.js library from the beginning and is based on the push/pull pattern. In simple terms, it allows you to retrieve the value (pull) and update or mutate it (push). A signal always has a value, and retrieving this value is done synchronously.</p><p>In Angular version 16, the pattern-based API will be integrated to enhance the performance of Angular’s change detection mechanism. Let’s understand <strong>why </strong>this change is beneficial 🤔?.</p><p>At the start of an Angular application, the framework overrides certain low-level browser APIs, such as addEventListener, using the Zone.js library. Zone.js is responsible for triggering change detection by listening to various events like clicks, mouseovers, HTTP requests, and timers (setTimeout, setInterval).</p><p>Whenever something changes in your application, a change detection process is performed, and your page is refreshed. Angular organizes your application as a component tree, where each component is associated with a change detector. By default, when a change occurs in any child component, the entire tree is re-evaluated, regardless of each component’s dependencies. This process is called dirty checking.</p><p>Even if your application’s change detection is set to OnPush mode, the change detection cycle still traverses the entire component tree. However, with OnPush components that have no change dependencies, they won’t be re-evaluated unnecessarily.</p><p>As a result, the default change detection in Angular is not optimal. To address this issue, the integration of the Signal pattern will be helpful. With Signals, the granularity of change detection is at the level of the signal variable itself. This means that change detection will occur at the component level only when the associated signal changes, without the need to traverse the entire component tree or rely on Zone.js. In the future, Zone.js might even become optional.</p><p>By incorporating the Signal pattern, Angular aims to improve the efficiency of change detection, leading to better performance and more streamlined updates within your application.</p><pre>import { Component, computed, effect, signal } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  template: `<br>    &lt;h1&gt;Calculate Area&lt;/h1&gt;<br>    &lt;p&gt;Answer : {{ area() }}&lt;/p&gt;<br>    &lt;button (click)=&quot;calculateArea(10,10)&quot;&gt;Click&lt;/button&gt;<br>  `,<br>})<br><br>export class App {<br>    height = signal(5);<br>    width = signal(5);<br>    area = computed(() =&gt; this.height() * this.width());<br>    constructor() {<br>      effect(() =&gt; console.log(&#39;Value changed:&#39;, this.area()));<br>    }<br>    calculateArea(height: number, width: number) {<br>      this.height.set(height);<br>      this.width.set(width);<br>    }<br>}</pre><p>In this example, I have created a computed value area and two signals named height and width. When the values of the signals are changed by invoking the calculateArea() function, the computed value will be updated and displayed in the template. Here is a working <a href="https://stackblitz.com/edit/angular-7hfstb?file=src/main.ts">Stackblitz example</a> for you to try it.</p><p>Although this looks fantastic, Angular has not abandoned zone.js and RxJS. Signals are an optional feature, and Angular will still work without them.</p><h3>Server-Side Rendering</h3><p>Angular 16 has addressed the lack of server-side rendering (SSR) support, which was a major drawback compared to React. Previously, Angular used destructive hydration for SSR, resulting in issues like screen flickering and negatively impacting user experience.</p><p>However, Angular 16 introduces non-destructive hydration to overcome these problems. With non-destructive hydration, the DOM is not destroyed when the client app is downloaded and bootstrapped. Instead, it enhances the existing DOM by adding client-side features like event listeners, preserving the rendered content.</p><p>It’s important to note that non-destructive hydration in Angular 16 is currently in the developer preview stage. To enable it, you can include provideClientHydration() as a provider when bootstrapping the application.</p><p>In simpler terms, Angular 16 has improved server-side rendering by introducing non-destructive hydration, which avoids issues like screen flickering. The rendered content is preserved and enhanced with client-side features, resulting in a smoother user experience.</p><pre>import {<br> bootstrapApplication,<br> provideClientHydration,<br>} from &#39;@angular/platform-browser&#39;;</pre><pre>...</pre><pre>bootstrapApplication(RootCmp, {<br> providers: [provideClientHydration()]<br>});</pre><p>According to the official Angular release note, this is just the beginning. They plan to explore partial hydration as the next step and work on several developer requests. You can find more about the Angular SSR development plan <a href="https://blog.angular.io/whats-next-for-server-side-rendering-in-angular-2a6f27662b67">here</a>.</p><h3>Route params mapping</h3><pre>export const routes: Routes = [<br> { path: &#39;search:/id&#39;,<br>   component: SearchComponent,<br>   resolve: { searchDetails: searchResolverFn }<br> }<br>]</pre><p>Previously, in versions of Angular before 16, developers had to use the ActivatedRoute service to retrieve URL parameters, query parameters, and associated data. This service was necessary for accessing and working with the information contained in the URL. However, the specific changes or improvements related to this functionality in Angular 16.</p><pre>@Component({...})<br>export class SearchComponent {<br>  readonly #activateRoute = inject(ActivatedRoute);<br>  readonly id$ = this.#activatedRoute.paramMap(map(params =&gt; params.get(&#39;id&#39;);<br>  readonly data$ = this.#activatedRoute.data.(map(({ searchDetails }) =&gt; searchDetails)<br>}</pre><p>With Angular 16 it will no longer be necessary to inject the ActivatedRoute service to retrieve the various route parameters because these can be directly binded to component inputs.</p><p>To activate this functionality, for an application that uses the module system, the option to activate is in the RouterModule options.</p><pre>RouterModule.forRoot(routes, { bindComponentInputs: true })</pre><p>For a standalone application, this is a function to call.</p><pre>provideRouter(routes, withComponentInputBinding());</pre><p>Once the functionality is activated, the component is very simplified.</p><pre>@Component({...})<br>export class SearchComponent {<br>  @Input() id!: string;<br>  @Input() searchDetails!: SearchDetails<br>}</pre><h3>Required Input</h3><p>A much-awaited feature for the community was the ability to make certain inputs required.</p><p>From version 16, making an input required will be a simple configuration object to be passed to the metadata of the input annotation.</p><pre>export class App {<br>  @Input({ required: true }) name: string = &#39;&#39;;<br>}<br><br>// or<br>@Component({<br>  ...<br>  inputs: [<br>    {name: &#39;name&#39;, required: true}<br>  ]<br>})</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-qcvat9%3Fembed%3D1%26file%3Dsrc%252Fmain.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-qcvat9%3Ffile%3Dsrc%252Fmain.ts&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-qcvat9%2F688a7f74615d0a21849862fd126fc8e0&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b142fb3420cbc98ab8a1b3bdb91c233/href">https://medium.com/media/4b142fb3420cbc98ab8a1b3bdb91c233/href</a></iframe><h3>DestroyRef injector</h3><p>Angular version 16 introduces a new provider called DestroyRef, which enables developers to register destroy callbacks for specific lifecycle scopes. This feature applies to various Angular entities such as components, directives, pipes, embedded views, and instances of Environment Injector. The DestroyRef provider provides a convenient way to handle cleanup operations when these entities are destroyed, ensuring efficient resource management within Angular applications.</p><pre>@Component({...})<br>export class AppComponent {<br>  constructor() {<br>    inject(DestroyRef).onDestroy(() =&gt; {<br>      // Writte your cleanup logic<br>    })<br>  }<br>}</pre><p>With this new provider, Angular allows us to share some classic cleaning logic such as the unusubscription of our observables.</p><pre>export function destroyed() {<br>  const replaySubject = new replaySubject(1);<br><br>  inject(DestroyRef).onDestroy(() =&gt; {<br>    replaySubject.next(true);<br>    replaySubject.complete();<br>  });<br><br>  return &lt;T&gt;() =&gt; takeUntil&lt;T&gt;(replaySubject.asObservable());<br>}</pre><h3>RxJS interoperability</h3><p>You’ll be able to easily “lift” signals to observables via functions from @angular/core/rxjs-interop which is in developer preview as part of the v16 release!</p><p>Here’s how you can convert a signal to observable:</p><pre>import { toObservable } from &#39;@angular/core/rxjs-interop&#39;;</pre><pre>@Component({...})<br>export class App {<br>  count = signal(0);<br>  count$ = toObservable(this.count);</pre><pre>  ngOnInit() {<br>    this.count$.subscribe(() =&gt; ...);<br>  }<br>}</pre><p>…and here’s an example how you can convert an observable to signal to avoid using the async pipe:</p><pre>import {toSignal} from &#39;@angular/core/rxjs-interop&#39;;</pre><pre>@Component({<br>  template: `<br>    &lt;li *ngFor=&quot;let row of data()&quot;&gt; {{ row }} &lt;/li&gt;<br>  `<br>})<br>export class App {<br>  dataService = inject(DataService);<br>  data = toSignal(this.dataService.data$, []);<br>}</pre><p>Angular users often want to complete a stream when a related subject completes. The following illustrative pattern is quite common:</p><pre>destroyed$ = new ReplaySubject&lt;void&gt;(1);</pre><pre>data$ = http.get(&#39;...&#39;).pipe(takeUntil(this.destroyed$));</pre><pre>ngOnDestroy() {<br>  this.destroyed$.next();<br>}</pre><p>We are introducing a new RxJS operator called takeUntilDestroyed, which simplifies this example into the following:</p><pre>data$ = http.get(&#39;…&#39;).pipe(takeUntilDestroyed());</pre><p>By default, this operator will inject the current cleanup context. For example, used in a component, it will use the component’s lifetime.</p><p>takeUntilDestroyed is especially useful when you want to tie the lifecycle of an Observable to a particular component’s lifecycle.</p><h3>esbuild-Based Build System:</h3><p>Angular 14 introduced a new JavaScript bundler called EsBuild. It offers fast build times, reducing them by around 40%. Initially, it could only be used for builds and not during development. However, in the next Angular release, EsBuild can also be used during development with Vite. Simply update the angular.json file to activate this feature. Overall, EsBuild improves the speed and efficiency of Angular development and build processes.</p><pre>&quot;architect&quot;: {<br> &quot;build&quot;: {<br>  &quot;builder&quot;: &quot;@angular-devkit/build-angular:browser-esbuild&quot;,<br>     &quot;options&quot;: { ... }</pre><h3>Standalone Project Support</h3><p>Angular 14 started supporting standalone components, which are independent of modules. Angular 16 takes this to the next level by supporting standalone project creation.</p><p>Angular 16 has a flag to create a standalone project through the Angular CLI. You have to execute ng new command with the –standalone flag. Then, it will generate a project without NgModules.</p><pre>ng new --standalone</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*XWO34CqCssjIqNOF.png" /></figure><h3>Other Features</h3><ul><li>Auto-importing of components and pipes through the language service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NFAXj1TDT0N8d0fY.gif" /></figure><ul><li>Support for TypeScript 5.0, ECMAScript decorators, service workers, and SCP through the CLI.</li><li><strong>CSP support for online styles</strong>.</li></ul><p>Inline style elements that Angular includes in the DOM for component styles violate the default style-src <a href="https://angular.io/guide/security#content-security-policy">Content Security Policy (CSP)</a>. To fix this, they should either contain a nonce attribute or the server should include a hash of the style’s content in the CSP header. Even though at Google we did not find a meaningful attack vector to this vulnerability, many companies enforce strict CSP, leading to the popularity of a <a href="https://github.com/angular/angular/issues/6361">feature request</a> on the Angular repository.</p><p>In Angular v16, we’ve implemented a new feature spanning the framework, Universal, CDK, Material, and the CLI which allows you to specify a nonce attribute for the styles of the components that Angular inlines. There are two ways to specify the nonce: using the ngCspNonce attribute or through the CSP_NONCE injection token.</p><p>The ngCspNonce attribute is useful if you have access to server-side templating that can add the nonce both to the header and the index.html when constructing the response.</p><pre>&lt;html&gt;<br>&lt;body&gt;<br>  &lt;app ngCspNonce=&quot;{% nonce %}&quot;&gt;&lt;/app&gt;  <br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The other way of specifying the nonce is through the CSP_NONCE injection token. Use this approach if you have access to the nonce at runtime and you want to be able to cache the index.html:</p><pre>import {bootstrapApplication, CSP_NONCE} from &#39;@angular/core&#39;;<br>import {AppComponent} from &#39;./app/app.component&#39;;</pre><pre>bootstrapApplication(AppComponent, {<br>  providers: [{<br>    provide: CSP_NONCE,<br>    useValue: globalThis.myRandomNonceValue<br>  }]<br>});</pre><ul><li>Self-closing tags.</li></ul><pre>&lt;super-duper-long-component-name [prop]=&quot;someVar&quot;&gt;&lt;/super-duper-long-component-name&gt;<br><br>&lt;super-duper-long-component-name [prop]=&quot;someVar&quot;/&gt;</pre><ul><li>Cease of support for ngcc and TypeScript 4.8.</li></ul><p>In the latest version 16 of Angular, the ngcc and all other view engine-related codes have been removed, reducing the angular bundle size. Additionally, the Angular View Engine libraries can no longer be used in v16+. Though these libraries were not officially supported but are a hard break in compatibility. This completes the transition of Angular from View Engine to Ivy complete.</p><h3>References:</h3><p><a href="https://dev.to/this-is-angular/whats-new-in-angular-16-375b">What&#39;s new in Angular 16</a></p><p><a href="https://blog.angular.io/angular-v16-is-here-4d7a28ec680d">https://blog.angular.io/angular-v16-is-here-4d7a28ec680d</a></p><p><a href="https://www.syncfusion.com/blogs/post/angular-16-top-7-features.aspx">https://www.syncfusion.com/blogs/post/angular-16-top-7-features.aspx</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac99edc02c20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Node]]></title>
            <link>https://medium.com/@megha.d.parmar2018/asynchronous-node-62f72d7d8ff8?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f72d7d8ff8</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[call-stack]]></category>
            <category><![CDATA[synchronous-programming]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 06:13:38 GMT</pubDate>
            <atom:updated>2023-06-27T06:21:47.198Z</atom:updated>
            <content:encoded><![CDATA[<p>NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications.</p><p>Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.</p><h4><strong>Event loop:</strong></h4><p>Node handles requests using an <strong>Event loop</strong> inside the NodeJS environment.</p><p>An event loop is an <strong>event-listener</strong> which functions inside the NodeJS environment and is always ready to listen, process, and output for an <em>event</em>.</p><p>An event can be anything from a mouse click to a keypress or a timeout.</p><h3><strong>Synchronous programming and Asynchronous programming</strong></h3><p><strong>Synchronous programming</strong> means that the code runs in the sequence it is defined. In a synchronous program, when a function is called and has returned some value, only then will the next line be executed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-g3ez3o%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-g3ez3o%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-g3ez3o%2Fd93dfa1eeb3a8583f391fe12182d81ed&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad7de22ef20f5a89c55c6cf5846bc4c6/href">https://medium.com/media/ad7de22ef20f5a89c55c6cf5846bc4c6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*J2TbzBBtBJ7vD0DjQ_K_Gg.jpeg" /></figure><p><strong>Asynchronous programming</strong>, on the other hand, refers code that doesn’t execute in sequence. These functions are performed not according to the sequence they are defined inside a program but only when certain conditions are met.</p><p>For example, setTimeOut() performs a task after a delay of a certain predefined number of miliseconds.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-enn4jk%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-enn4jk%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-enn4jk%2Fdd563928c6f1326521c4201e130e60dc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aab1d9b1e87dbca5dca70e4b73fec23/href">https://medium.com/media/0aab1d9b1e87dbca5dca70e4b73fec23/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*8JI0AY6YsNkvarD0YlrjBQ.gif" /></figure><h4><strong>Callback Function:</strong></h4><p>A callback is a simple function that’s passed as a value to another function, and will only be executed when the event happens. We can do this because JavaScript has first-class functions, which can be assigned to variables and passed around to other functions (called <strong>higher-order functions</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*jYcKxqym0ir_JQ4njRWFNQ.jpeg" /></figure><h4><strong>Handling errors in callbacks</strong></h4><p>How do you handle errors with callbacks? One very common strategy is to use what Node.js adopted: the first parameter in any callback function is the error object: <strong>error-first callbacks</strong></p><p>If there is no error, the object is null. If there is an error, it contains some description of the error and other information.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-gfbxap%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-gfbxap%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-gfbxap%2F3dd22ad5e07a45660d183bbc8476ba73&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cec72cd20de96cf206e0a2b58db0edf/href">https://medium.com/media/3cec72cd20de96cf206e0a2b58db0edf/href</a></iframe><h4><strong>Async/Await:</strong></h4><p>The <strong>async function</strong> declaration declares an async function where the await keyword is permitted within the function body. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-uieej5%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-uieej5%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-uieej5%2Fe72a2eaaa89336ad5ae16535b2521401&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c06f776d69603074faf86c330386950/href">https://medium.com/media/7c06f776d69603074faf86c330386950/href</a></iframe><h3>Callbackhell</h3><p>In Node.js, callback hell refers to a situation where you have nested or chained callbacks, making the code difficult to read and maintain. It typically occurs when dealing with asynchronous operations, such as making multiple API requests or performing I/O operations.</p><p>Here’s a simple example to illustrate callback hell:</p><pre>getDataFromAPI(function (data) {<br>  processData(data, function (processedData) {<br>    saveDataToFile(processedData, function (success) {<br>      if (success) {<br>        console.log(&quot;Data saved successfully!&quot;);<br>      } else {<br>        console.log(&quot;Error while saving data.&quot;);<br>      }<br>    });<br>  });<br>});</pre><p>In this example, we have three asynchronous operations: getDataFromAPI, processData, and saveDataToFile. Each operation requires a callback function to handle the result or error.</p><p>As you can see, the callbacks are nested within each other. This nesting becomes more complex as the number of asynchronous operations increases, leading to an indentation pyramid commonly referred to as callback hell.</p><p>The main problems with callback hell are:</p><ol><li>Readability: The code becomes difficult to read and understand due to the deep nesting of callbacks.</li><li>Maintainability: Making changes or adding more functionality to the code becomes cumbersome and error-prone.</li><li>Error handling: Error handling becomes challenging, and it’s easy to overlook potential errors or introduce bugs.</li></ol><p>To mitigate callback hell, several solutions have emerged over time, such as Promises, async/await, and libraries like async.js and bluebird. These alternatives provide more readable and maintainable code by avoiding excessive callback nesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f72d7d8ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node Js with Command Line Argument and dotenv]]></title>
            <link>https://medium.com/@megha.d.parmar2018/node-js-with-command-line-argument-e0a60af0574e?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a60af0574e</guid>
            <category><![CDATA[nodejs-dotenv]]></category>
            <category><![CDATA[nodejs-with-cmd-line-argu]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Wed, 31 May 2023 12:10:13 GMT</pubDate>
            <atom:updated>2023-05-31T12:11:00.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5R5olTbe_CZlhMoOx9Ukg.jpeg" /></figure><p>Command-line arguments (CLI) are strings of text used to pass additional information to a program when an application is running through the command line interface of an operating system.</p><h3><strong>Parse command-line arguments method:</strong></h3><ol><li><strong>process.argv</strong></li><li><strong>yargs</strong></li></ol><h4><strong>process.argv:</strong></h4><p>It is the simplest way to receive arguments with the help of process.argv array. Node.js exposes this array for every running process in the form of <em>process.argv</em>. The first element of process.argv array is the file system path pointing to Node executable file. The second element is the path of the JavaScript file that is being executed and the rest array elements are the arguments passed via <em>cmd</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-zd9eyx%3Fembed%3D1%26file%3Dpackage.json&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-zd9eyx%3Ffile%3Dpackage.json&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-zd9eyx%2Fc6c377253d7b4c9e579022fac4657c69&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c56c86ecd11952484fae0342a1c6c4b/href">https://medium.com/media/9c56c86ecd11952484fae0342a1c6c4b/href</a></iframe><h3><strong>yargs:</strong></h3><p>Install <strong>yargs</strong> module using the following command:</p><p>npm install yargs — save</p><p>we can use the third library module such as <a href="http://yargs.js.org/docs/">yargs</a> to parse the arguments passed via <em>cmd</em>. In this module, you can pass arguments as a key-value pair and later access them with the help of a key. The <strong>.argv</strong> gets the arguments as a plain old object.</p><p>node index.js — language=javascript — ide=GFG_IDE command1 command2 — b — v</p><ul><li>argv.$0 contains the name of the script file which is to execute.</li><li>argv._ is an array containing each element not attached to an option(or flag) these elements are referred to as commands in yargs.</li><li>The flags such as argv.time, argv.b, etc become the property of the argv. The flags must be passed as –flag. Example: <strong><em>node app.js –b</em></strong></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-3llrna%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-3llrna%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-3llrna%2Fd7f92bc9f175b3b7558f6dddf019e95d&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/db61c22ac40cdc4b45afcdd7e760583b/href">https://medium.com/media/db61c22ac40cdc4b45afcdd7e760583b/href</a></iframe><h3><strong>Environment Variable:</strong></h3><p>Environment variables are very fundamental part of developing with Node.js or any server-side language. They always contain very sensitive data and doesn’t mean to be shared with outside world. You must make sure that your server is properly configured to make use of correct variables for both development and production environments. Any mistake can lead your server to crash.</p><p>Working with environment variable in Node.js is very easy and simple.</p><h4><strong>.env:</strong></h4><p>.env is a special file which is used to define environment variables in Node.js. It holds key=value pairs to define the variables.</p><p><strong><em>Make sure to ignore .env in the .gitignore before commiting any changes.</em></strong></p><p>One popular module is <a href="https://github.com/motdotla/dotenv">dotenv</a> (which i use) which can guide through the basic of .env file.</p><h4><strong>~ Creating the file</strong></h4><p>First create a file with name .env in the <em>root of the project</em> which contains all variable which will be injected in the environment by the dotenv.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-h2fx7t%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-h2fx7t%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-h2fx7t%2F5b571c53827b934257bb2cf9eca9b7bc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/208c118e9a278b80a66d51c5357406e0/href">https://medium.com/media/208c118e9a278b80a66d51c5357406e0/href</a></iframe><h4><strong>~ Configuring the dotenv</strong></h4><p>First install the dotenv package from the npm as a dev dependencies as we don’t need this in production.</p><p><strong>npm i -D dotenv</strong></p><h3><strong>References:</strong></h3><p><a href="https://www.geeksforgeeks.org/how-to-parse-command-line-arguments-in-node-js/">https://www.geeksforgeeks.org/how-to-parse-command-line-arguments-in-node-js/</a></p><p><a href="https://www.geeksforgeeks.org/how-to-read-command-line-arguments-in-node-js/">https://www.geeksforgeeks.org/how-to-read-command-line-arguments-in-node-js/</a></p><p><a href="https://dev.to/numtostr/environment-variables-in-node-js-the-right-way-15ad">https://dev.to/numtostr/environment-variables-in-node-js-the-right-way-15ad</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a60af0574e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node Js module]]></title>
            <link>https://medium.com/@megha.d.parmar2018/node-js-module-ab85fa48137d?source=rss-e3153e31b6df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab85fa48137d</guid>
            <category><![CDATA[nodejs-module-type-diff]]></category>
            <category><![CDATA[nodejs-module-types]]></category>
            <category><![CDATA[nodejs-module]]></category>
            <dc:creator><![CDATA[Megha D Parmar]]></dc:creator>
            <pubDate>Wed, 31 May 2023 10:18:35 GMT</pubDate>
            <atom:updated>2023-05-31T10:22:45.770Z</atom:updated>
            <content:encoded><![CDATA[<p>Modules are the collection of JavaScript codes in a separate logical file that can be used in external applications based on their related functionality. Modules are popular as they are easy to use and reusable.</p><h4><strong>How to create node module:</strong></h4><p><strong>Syntax:</strong></p><p>exports.function_name = function(arg1, arg2, ….argN) { <br> // function body <br>};</p><h4><strong>Modules are of three types:</strong></h4><ul><li>Core Modules</li><li>Local/Custom Modules</li><li>Third-party Modules</li></ul><h4><strong>Core Modules:</strong></h4><p>Node.js has many built-in modules that are part of the platform and come with Node.js installation. These modules can be loaded into the program by using the <strong>require</strong> function.</p><h4><strong>Syntax:</strong></h4><p>const module = require(‘module_name’);</p><p>The require() function will return a JavaScript type depending on what the particular module returns. The following example demonstrates how to use the Node.js http module to create a web server.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-3gkx7q%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-3gkx7q%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-3gkx7q%2Fb54648889040a4e24428b0d0fd29c208&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b689088a1bab92102dec6a98f6056c80/href">https://medium.com/media/b689088a1bab92102dec6a98f6056c80/href</a></iframe><p>In the above example, the require() function returns an object because the Http module returns its functionality as an object. The function http.createServer() method will be executed when someone tries to access the computer on port 3000. The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the response headers. The following list contains some of the important core modules in Node.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*JW-M-7irTqKKEpokuX7tkA.jpeg" /></figure><h4><strong>Local/Custom Modules:</strong></h4><p>Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-ufnytf%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fstackblitz-starters-ufnytf%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fstackblitz-starters-ufnytf%2Fdd2a1678f8709144cbdb11cce6bb6175&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/626b52afa8843e1d8da717f3cbc82fc4/href">https://medium.com/media/626b52afa8843e1d8da717f3cbc82fc4/href</a></iframe><p>Since this file provides attributes to the outer world via exports, another file can use its exported functionality using the require() function.</p><h4><strong>Third-party modules:</strong></h4><p>Third-party modules are modules that are available online using the Node Package Manager(NPM). These modules can be installed in the project folder or globally. Some of the popular third-party modules are Mongoose, express, angular, and React.</p><h4><strong>Example:</strong></h4><ul><li>npm install express</li><li>npm install mongoose</li><li>npm install -g @angular/cli</li></ul><h4><strong>CommonJS vs. ES modules in Node.js:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*43MY2G7aI5nGGrYZOK-mTg.jpeg" /></figure><h4>Global npm module and nodemon:</h4><blockquote><strong><em>npm install -g nodemon</em></strong></blockquote><p>When you run npm i nodemon nodemon is installed as a local project dependency, to run nodemon on the CLI you would have to provide the pull path to it&#39;s installation, typically you would want to make this reference in your project&#39;s package.json file&#39;s scripts property, for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*qaw0I2nFT4y31MqRMrV9Tw.jpeg" /></figure><p>This can then be executed by running npm run nodemon.</p><p>On the other hand running npm install -g nodemon or npm i -g nodemon installs nodemon on the global scope where it is referenced in your system PATH variable, that way you can easily call nodemon on the CLI and since it&#39;s full installation path is referenced in your system PATH variable it would execute like every other CLI command.</p><h3>References:</h3><p><a href="https://www.geeksforgeeks.org/how-to-create-modules-in-node-js/">https://www.geeksforgeeks.org/how-to-create-modules-in-node-js/</a></p><p><a href="https://www.geeksforgeeks.org/node-js-modules/">https://www.geeksforgeeks.org/node-js-modules/</a></p><p><a href="https://blog.logrocket.com/commonjs-vs-es-modules-node-js/">https://blog.logrocket.com/commonjs-vs-es-modules-node-js/</a></p><p><a href="https://stackoverflow.com/questions/73560510/what-is-difference-between-local-and-global-node-package-installation">https://stackoverflow.com/questions/73560510/what-is-difference-between-local-and-global-node-package-installation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab85fa48137d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>