Using a module's internal function as a callback in the "request" operation

Within my primary code, I execute the following:

var module = require('./module')

module.FooA(module.FooB);

The contents of module.js are as follows:

var request = require('request'); //using npm "request"

exports.FooB = function(data){ /*operations on data here*/ };

exports.FooA = function(callback){

    var url = some_link;

    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(body);
        };
    });

};

An issue arises where callback(body) does not execute even when the conditions are met. While using var result = request(url) and then exports.FooB(result) seems to resolve the problem, it is evident that this approach lacks the asynchronous nature of a callback function and may lead to complications.

What would be the correct method for defining a callback function in such a scenario? Is there a need for it at all, or could it possibly be synchronous and overlooked?

Answer №1

Ensure to utilize the first function callback parameters for handling errors, as this is a default practice in the core of node.js and can be beneficial for your project functions.

Following @ShanSan's advice, make use of console.log, console.error, or console.trace for debugging purposes.

For instance:

var request = require('request'); //using npm package "request"

exports.FooB = function(error, data){ /*operations on data go here*/ };

exports.FooA = function(callback){

    var url = some_link;

    request(url, function (error, response, body) {
        if (error || response.statusCode != 200) {
          // pass error to callback and you may simply return without additional code block below
          console.error('Error in request', error);
          return callback(error, null); 
        } 

        // code executes here if no errors are present

        // for more information, consider using console.log(request); or console.log(body);

        // remember to place error as the first parameter in callback functions 

        callback(null, body);
    });

};

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 method for obtaining the hostname of a socket?

Whenever a specific event is received from a connected socket, I need to send a request with my hostname and port as parameters. I had hoped to access this information directly from the socket object. However, due to the lack of documentation, I am unable ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

Setting up an NGINX server to route requests to a node server without a specified path

I have a server running Nginx with the following setup: server { listen 80; server_name example.ca www.example.ca; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

Solving Cross-Origin Resource Sharing (CORS) issues in a

I am utilizing the cors module within a Node application to handle CORS checks. Below is the code snippet: var corsOptions = { credentials: true, origin: function (origin, callback) { if (config.get('CORS').whitelist.indexOf(orig ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

What is the best approach for transforming a try-catch block into async-await when a promise is returned within a conditional statement?

I need assistance transitioning from using then-catch to async-await in my code. Below is the existing then-catch code: Source.findOne({ name: req.sourceName }) .then(sourceData => { //Existing code here ...

The presence of an imported node module that exports firebaseui results in jest tests failing due to the error message: "ReferenceError: window is not defined"

I created my own NPM package that includes various React components which utilize the firebaseui library. It's important to note that firebaseui requires the DOM to be present in order to function properly. In my index.ts, this is how I'm exporti ...

Monitor the HTTP response code in sails

I am working on logging every request that is being made to my sails application, however, I am facing an issue with logging the response associated with a request. To address this problem, I have created a custom middleware in the config/http.js file : ...

Tips for converting an image URL into a BLOB datatype in Mysql

I am facing an issue where I need to convert a URL (such as ) that is stored in a varchar column into a blob column in the same table, using only MySQL. My objective is to store the image directly in my table because there's a possibility that the URL ...

angular contains vulnerabilities of a moderate severity level

I am encountering an issue while trying to set up the json server for a web application I am developing using Angular. Can someone provide assistance in resolving this problem? The following dependencies are at risk due to vulnerable versions: node_m ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

Experiencing difficulties when attempting to invoke external functions

I have a server-side API built with nodejs, linked to a MySQL database using the knex npm package for handling CRUD operations, and express for request and response management. Picture this scenario: I have a controller file responsible for inserting data ...

How to manage a particular process ID in Node.js?

I am currently working on a node application that allows clients to control a program running on the server. The program needs to run in its own terminal window at all times. Here is the ideal scenario: When a client clicks a button, a command is executed ...

Error: No valid signatures were found for the given payload

After working with some stripe code, I decided to implement webhooks. I visited the official Stripe webpage, copied the source code provided for webhooks, but unfortunately it isn't functioning as expected. client.post('/webhook', express.ra ...

Express-Session Object Method

I am currently facing an issue with linking an object to an Express session. Below is the code I am using: var express = require('express'); var session = require('express-session'); // Defining an object named "engine" which simulate ...

Limiting the use of global variables or functions in Node.js

How can I restrict global variables and functions in Node.js? Similar to the 'require' method, I am looking to limit the use of the 'require' method. I do not want any Node applications to access "fs" in my custom Node framework buil ...

How can one utilize electron's webContents.print() method to print an HTML or text file?

Electron Version : 2.0.7 Operating System : Ubuntu 16.04 Node Version : 8.11.1 electron.js let win = new BrowserWindow({width: 302, height: 793,show:false}); win.once('ready-to-show', () => win.hide()); fs.writeFile(path.join(__dirname ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...

Turning videos into different formats on-the-fly with Node.js and avconv

I am currently developing a real-time video conversion demo application. The video file is parsed using the node-multiparty module, where the file's section is piped to avconv.stdin. Once processed, the chunk is then passed on to a write stream. Belo ...