Function cascading

I'm currently facing a slight confusion with the got module, available at https://www.npmjs.com/package/got. The sequence and structure of functions within this module has got me puzzled. It's clear that you can chain listeners and functions together like this:

 got.stream(link)
 .on('response', resp => {
   if (resp.statusCode != 200) this.emit('error', '!200')
 })
 .on('error', err => {
   console.log(err)
 })
 .pipe(somewhere)

The request module also utilizes this technique. However, my question is how can one avoid using .pipe if they only want it to occur under the condition resp.statusCode != 200? Given its prevalence in various request modules, there must be a fundamental concept associated with it that I haven't quite grasped.

Answer №1

If you choose not to chain it, there is no obligation to do so. In this particular scenario, it would be best to avoid chaining. Here's an uncomplicated instance of how you can achieve the desired result without using chaining:

const acquiredStream = acquired.stream(link);
acquiredStream.on('response', response => {
    if(response.statusCode == 200) {
        acquiredStream.pipe(specificDestination);
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

Requesting information asynchronously returns a positive response

I wrote the following code: if (venue_exists(instagramUserID)){ alert('A'); }else { alert('C'); } function venue_exists(instagramUserID) { $.get( "/venues/" + instagramUserID, function( ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

Deploying local NPM modules with npm link to Heroku servers

While using npm link to incorporate my local modules into my app, I encountered an issue. It works perfectly on my machine, but after running grunt and deploying it to Heroku, the system claims that my module cannot be found! Currently, all my files are c ...

What could be the reason behind getting two log files in log4js?

There seems to be an issue with my logger configuration in a Node.js script: const log4js = require('log4js'); log4js.configure({ appenders: { out: { type: "dateFile", filename: conf.logsFolder+"e ...

Tips for concealing API endpoints in a React Native Android application

I've developed a nodejs, express, and mongodb API that is currently hosted on Heroku. My next step is to utilize this API URL within my React Native Android app. Unfortunately, I'm facing an issue where the API URL could potentially be exposed to ...

Is it possible to remove individual items from a FlatList by clicking on them and updating the state?

I have a FlatList displaying items from an array called data. My goal is to remove each item individually by clicking on it, but currently when I click on one item, all items are deleted at once. Any suggestions on how to address this issue? Here's ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

What is the solution for the error message "Unhandled Runtime Error" with the description "TypeError: videoRef.current.play is not a function"?

I am currently working on implementing custom controls for a video on a Nextjs website. When using a standard HTML <video> component, the code functions as expected and clicking the custom play button successfully plays the video. However, when I swi ...

Encountering an error with the node module timestampnotes: 'command not recognized'

I am encountering an issue while trying to utilize a npm package called timestamp notes. After executing the following commands: $npm install timestampnotes $timestamp I receive the error message: timestamp:126: command not found: slk Subsequently, I ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Is it possible to exclude certain static files from being served in express.static?

const express = require('express'); const app = express(); app.use('/app', express.static(path.resolve(__dirname, './app'), { maxage: '600s' })) app.listen(9292, function(err){ if (err) console.log(err); ...

Error: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON." const functions = require("firebase-functions"); const axios = ...

Encountering an undisclosed CORS error on all requests from Angular frontend to NodeJS Express Server during preflight 200

After thorough testing with Postman, my backend server is functioning properly and generating the desired responses for all requests. However, my Angular app is encountering an unknown CORS error on every request despite receiving a 200 Preflight response ...

Tips for resolving the npm ResourceUnavailable issue

Hey there! I'm currently experimenting with React. In my folder, I've got nodejs along with npm and npx files installed. While debugging, I've deleted and reinstalled this folder multiple times. However, no matter what directory or command I ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...