What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the code reaches line 46 in the file. This section of the code utilizes fs to update another file's contents by adding the user-inputted information from the webpage for this application.

const fs = require('fs');

module.exports = function(app, path) {

    app.get('api/friends', function(req, res) {
        fs.readFile("app/data/friends.js", "utf8", function(err, data) {
            if (err) throw err;

            else {
                res.json(JSON.parse(data));
            }
        });
    });

    app.post('/api/friends', function(req, res) {
        let results = [];

        const postResponse = JSON.stringify(req.body);

        fs.readFile('app/data/friends.js', function (err, data) {
            if (err) throw err; 

            let friendFile = JSON.parse(data);
            console.log(friendFile[0].answers);
            let closestMatch = 0;
            let matchScore = 999999999999999;

            for (let i = 0; i < friendFile.length; i++) {
                console.log(friendFile.length);
                let spaceBetween = 0;
                for (let j = 0; j < friendFile[i].answers.length; j++) {
                    // ['answers[]'][j]
                    console.log(req.body.answers[j]);
                    spaceBetween += Math.abs((parseInt(req.body.answers[j]) - parseInt(friendFile[i].answers[j])));
                }
                if (spaceBetween <= matchScore) {
                    matchScore = spaceBetween;
                    closestMatch == i;
                } 
            }

            results.push(friendFile[closestMatch]);

            friendFile.push(JSON.parse(postResponse));

            fs.writeFile("app/data/friends.js", JSON.stringify(friendFile));
                res.send(results[0]);
        })
    })
}

My goal is for this code to modify the friends.js file by incorporating all the information provided by the user through the survey responses. Additionally, it should display the user's closest friend match on the page based on their answers.

Answer №1

To ensure successful file writing, remember to include a callback function in your writeFile method call

const errorHandler = (error) => {
 if (error) throw error;
 console.log('File saved successfully!');
};
fs.writeFile("app/data/friends.js", JSON.stringify(friendData), errorHandler);

Answer №2

Seems like this is an Express application, right? Let's make a slight modification...

fs.writeFile("app/data/friends.js", JSON.stringify(friendFile));

...to...

fs.writeFile("app/data/friends.js", JSON.stringify(friendFile), function (err) {
  if (err) {
    res.sendStatus(500) // Inform the client of an internal server error
    throw err; // Handle the error in another way if needed.
  }

  // You can add additional code to execute after the file has been written to disk here.
  // This part won't be reached if there was an error earlier.
})

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

The first div should be hidden when the toggle is activated

I am currently working on a CRUD project and incorporating some Javascript/JQuery into it. I have a button labeled "Add", which, when clicked, displays a specific div element. However, I'm facing an issue where the div is already visible before the us ...

Automated browsing: identifying the difference between AJAX and iframes

During my automated requests (scheduled at specific times, without user involvement), I have noticed that xmlHttpRequest includes extra http headers. In order for the server not to be able to distinguish these requests as automated (they should appear exa ...

Utilizing CakePHP 3.0 with jQuery UI for an autocomplete feature

Seeking assistance on why the current code isn't functioning. The objective is to retrieve data from the index controller to search and obtain JSON data. No requests are being made, and there are no visible results. New to CakePHP 3.0, I am attemptin ...

The functionality of Javascript is being compromised when utilizing ng-repeat

Just recently diving into the world of AngularJs while developing a website. I've successfully retrieved data from Rest services on a page, and used ng-repeat to display it. The issue arises when I have a regular javascript element on the page that i ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Parsing case class objects in Scala using the JSON4S library

I have defined some case classes as shown below: sealed trait Type case object Apple extends Type case object Banana extends Type case object Orange extends Type case class Fruit(name: String, type: Type) In addition, there is an endpoint specified in S ...

What is the best way to adjust the scroll speed within a specific element using React?

Hey there, I'm currently working on adjusting the scroll animation of a div (MUI Container) to make it smoother and slower. I've spent some time searching online for a solution but haven't found anything helpful so far... By the way, I' ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

When a child is added to a parent in Angular UI Tree, it automatically appears in all parent nodes as well

I've been experimenting with the drag and drop feature of Angular UI Tree, and I've encountered a puzzling issue. The JSON data is fetched from my services. Upon receiving it in my controller, I need to format it correctly by adding an empty arra ...

Task: Choose MySQL option and Retrieve JSON data

I have a question regarding implementing a function in a separate module file and calling it within a route to retrieve query data: function getSobre() { return new Promise((resolve, reject) => { db.query(`SELECT * FROM sobre ORDER BY cod ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

Guide to generating a multi-depth JSON output through a SQL query in SQL Server 2016

Can a multi-level JSON string be created in SQL Server 2016? I have a table named "patient_data" structured as shown below: The desired output is to generate a JSON string in SQL Server similar to the following format: { "patient":[ { "key":" ...

Error: Unable to execute candidate.toLowerCase as a function

Encountering the following errors: `Uncaught TypeError: candidate.toLowerCase is not a function. I am utilizing the AutoComplete API within Material UI, however, when I search in the input field, it leads me to a blank page. This is my current code snippe ...

Regular occurrences of heap memory exhaustion within a node.js application running in a docker container

My node.js application consists of 16 microservices, a docker image, and is hosted on the Google Cloud Platform using Kubernetes. However, when handling API requests from just 100 users, some of the main docker images are crashing due to heap out of memor ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row. var myMatrix = []; var rows = 5; var columns = 3; for (var i = 0; i < rows; i++) { var temp = 1; myMatrix[i] = [i]; for (var j = 0; j < columns; j++) ...

Parsing Json with Unicode characters on Android is quite a task

My SQL server collation is UTF8 Unicode. My PHP works fine and my Android project is working fine with normal characters, but in the case of Arabic characters, it displays an error "Error parsing JSON" on line 233 in the activity listed below. I have tried ...

Tips for applying CSS styles to the active page link

Check out the code below: Is there a way to assign a specific class to the current page link so that the mouse cursor will display as default rather than changing to a hand icon? I'm looking for a solution where I can apply a class to the active lis ...

I'm currently troubleshooting the code for the Gallery project. The gallery is supposed to have 4x4 grids, but for some reason, the grids are

It seems like I am struggling to identify the exact issue. The display on mobile looks fine but not on desktop. I attempted to tweak the isotope configuration without success. Even manipulating the server-side code didn't reveal any obvious problems. ...

The dataset remains undefined within the context of Vue.js

I am attempting to utilize the dataset property in Vue to retrieve the data-attribute of an element. Here is how I am implementing it: <ul id="filter"> <li><a class="filter-item" v-on:click="filterItems" data-letter="a" href="#"> ...