Utilizing only requirejs to pipe the json body

Recently, I've switched to using requestjs and so far it's been working well for me. However, I'm curious if there's a way to pipe in a similar manner to handling promises:

function foo(url) {
  return request({ "url": url, "json": true })
}
let result = foo("https://jsonplaceholder.typicode.com/posts/1")
result.pipe(process.stdout)
result.on('data', console.log)
  • Using pipe, I can't directly access the object itself, which limits my ability to only stream the body.
  • Additionally, the on method doesn't adhere to my specifications for parsing the response as JSON.

As a result, I'm unable to simply extract the JSON data I receive. While I could use JSON.parse, I'm hoping to find a more straightforward way of handling the response (similar to promises) as I feel like there might be a greater solution that I'm overlooking.

Answer №1

Do you have a specific requirement for using streams? You always have the option to encapsulate the request in a promise.

Although this explanation is quite advanced, it should point you in the right direction.

function sendRequest(parameters) {
  return Promise((resolve, reject) => {
    request(parameters, (error, response) => {
      if (error) {
        return reject(error);
      }
      return resolve(response);
    };
  });
}

const parameters = {
  url: 'foo.com',
  method: 'GET',
  json: true,
};

sendRequest(parameters)
  .then(response => {
    if (response.statusCode === 200) {
      return Promise.resolve(response.body);
    } else if (response.statusCode === 404) {
      const error = {
        message: 'Not Found',
        code: 404,
      };
      return Promise.reject(error);
    }
  })
  .then(body => // perform operations on the data)
  .catch(error => // handle the error);

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 add a dictionary to a JSON file without compromising the integrity of the JSON structure?

Before I explain my issue, I want to clarify that this is not a duplicated problem; it is unique. I am trying to add data to a dictionary within a JSON file using the code below. Please note that items like k['Process'] are sourced from another ...

"Retrieve and set tab layout titles dynamically using JSON data in an Android application

I am looking to extract the title data from a JSON file and display it in my tab layout. Currently, I manually set the tab titles in the MainActivity.java file. How can I parse the JSON data to populate my tab layout with the titles? Below is the code sni ...

Make sure to utilize the className attribute when styling a Material-UI component

I am attempting to apply CSS styles to a Material-UI component. defined in MyCss.css .trackTitle { color:white; } located in myComponent.js import "./MyCss.css" <Grid container item xs={1} className="trackTitle"> change col ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

What could be causing my YAML value to be undefined when I try to read it in JavaScript, despite it being defined in every other

I have been attempting to access a YAML file from my local directory. While I am able to read the file, the data within it appears to be undefined. The error message that I am encountering is as follows: https://i.sstatic.net/yXC0H.png Here is an exampl ...

How can I create a clickable <div> element containing multiple links and trigger only one action?

Within my code, there is a <div> element that has been made clickable. Upon clicking this <div>, the height and text expand using the jQuery function $(div).animate();. While this functionality works as intended, I am encountering a slight issu ...

Using React client to accept messages from a Socket.io server: A guide

I have a setup where a Node.js server with Socket.io is used to send messages between React clients. Currently, I can send a message from Client 1 to Client 2, but the recipient must click a button to view the message on their screen. I am trying to make i ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

PHP contact form with AJAX functionality without page redirection

I'm currently working on a page that includes a contact form. The issue I'm facing is that when I click on "submit," the form redirects me to another page. What I actually want is for the page not to redirect, but instead display the success mes ...

Printing a webpage directly without the need for a print preview

Is there a way to automatically print a web page using JavaScript? Specifically, I want the printing process to be initiated with one click, without having to go through a print preview. The page in question contains both text and images, and I require a ...

Updating an HTML input field property with JavaScript is not reflecting the changes

I am currently working on a form with two fields: stationery type and stationery request quantity. The stationery request quantity field only accepts numerical input. The minimum quantity that can be entered in this field depends on the value selected in t ...

Issues connecting to servicenow have been detected

I encountered an error while attempting to connect to ServiceNow using JSON. Here is the code I am trying to execute: from servicenow import ServiceNow from servicenow import Connection conn = Connection.Auth(username='admin.main', password=&ap ...

Create a mapping in Go that uses integers as keys and struct values,

Looking for a way to convert a map[int] to a user-defined struct in Go: Below are the details of the data schemas. type Recommendation struct { Book int `json:"book"` Score float64 `json:"score"` } Here is the process of json marshaling: u ...

"Uncovering a memory leakage issue within a recursive polling function in JavaScript

Current issue in need of resolution: My team and I are currently working on a large application that was initially released around two years ago. We are in the process of adding a new "always-on" status screen to the application, which will be the default ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

How can I initiate an event in YUI3 framework?

If I have a click event on a link or button, how can I trigger the same click event through another action on the page? let myButton = Y.one('.button'); myButton.on('click', function() { // code }); I noticed YUI3's fire() me ...

Leverage Html5 to open and retrieve data from an Excel document

Is there a method to access excel file data using HTML5 while uploading the file on the client side? I have come across the use of reader in JavaScript, but unsure how it can be helpful in this scenario. Is there a way to read excel file data seamlessly ...

Locate the closest point among a set of coordinates to a specified point

I have a situation where I have an object that contains latitude and longitude attributes. My goal is to find the closest match in an array of similar objects by considering both latitude and longitude. obj = {latitude: 55.87, longitude: 4.20} [ { & ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...