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

Error: Authorization required to access server-side resource [POST http://localhost:3000/serverSide] - Status

I'm having an issue with sending a username and password from an HTML file to a Javascript file that queries an employee table for authentication. The problem arises when the username and password are set to undefined in my serverSide.js file, prevent ...

javascript add items to a container

I created a looping animation that features dynamic words, but I'm struggling to append all the spans into the <div id"wordcloud"></div>. Any assistance with this would be greatly appreciated. var interval = 100; var width = 800; var he ...

A guide to storing a JavaScript variable in a MySQL database using Express.js

Looking for some guidance on node js and expressjs framework. While developing a web application, I've encountered an issue with saving data into the database. Everything seems to be set up correctly, but the data stored in the variable (MyID) is not ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Tips on incorporating negation in npm script's glob pattern usage?

I have been struggling to create a clean npm script that works properly. Every time I try, I either encounter an error in the console or the intended outcome doesn't occur. My goal is to remove all root JavaScript files except for certain config files ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...

methods for sorting firestore data in react on client side

Fetching data from firestore and applying filters const [projects, setProjects] = useState([]); const fetchData = (sortBy = "NAME_ASC") => { const unsubscribe = firebase .firestore() .collection("projects") ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

The styling of divIcons in React Leaflet Material UI is not applied as expected

When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet. Below you can find the code for the project ...

Deciding whether an altered image has been successfully loaded

Currently, I am stuck on a minor point while creating a small gallery using jQuery. The code snippet looks like this: <script type="text/javascript> $(document).ready(function(){ $('#thumb1').click(function(){ $('#fullimage ...

transforming milliseconds into date format suitable for JQGrid styling

My Jqgrid is pulling data from a PHP file that returns JSON. The date constraint in the JSON is in milliseconds and I need to convert it to a regular date format. I have been searching for a solution and came across one that almost works: formatter:&apo ...

Modifying the HTML attribute value (of input) does not impact the value property

After inputting a single tag, I ran the following code in my Chrome console: https://i.stack.imgur.com/ySErA.jpg The result was unexpected for me. According to what I have read in a book, when I change an HTML attribute, the corresponding property should ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

Tips for managing the background color of a box when the function is constantly refreshing in Internet Explorer

function process(Objects) { var objectId = Objects; displayContent(objectId); } function displayContent(objectId) { var boxId = objectId.id; var color = ret ...