GET method returns an empty array in the express node server

app.get('/:user/:tag', function (req, res) {
 fs.readdir( 'api'+path.sep+req.params.user, function (err, files) {
    var tweets=[];
    for (var i =1, j=files.length ; i <j; i++)
    {
          fs.readFile('api'+path.sep+req.params.user+path.sep+files[i],'utf8', function (err, data)
           {
                data=JSON.parse(data);
                if (data.tag==req.params.tag){tweets.push(data);};         
           });
    };
    res.send(tweets);
 });
});

It appears that the issue lies with the callbacks in the fs method, and despite my efforts, I have been unable to resolve it for quite some time.

Answer №1

Absolutely, using fs.readFile() is an asynchronous method which means it will not wait for the response and might result in empty tweets being returned. Give this code a try

        app.get('/:user/:tag', function (req, res) {
         fs.readdir( 'api'+path.sep+req.params.user, function (err, files) {
if(files.length==0){
res.send([]);
}else{
            var tweets=[];
            for (var i =0, j=files.length ; i <j; i++)
            {
                  fs.readFile('api'+path.sep+req.params.user+path.sep+files[i],'utf8', function (err, data)
                   {
                        data=JSON.parse(data);
                        if (data.tag==req.params.tag){tweets.push(data);}; 
                        if(i==j-1){
                            res.send(tweets);
                          }        
                   });
            };
           }
         });
        });

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

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

Seeking guidance on designating an additional disk for fs.readdir(path) within an Electron-vue application?

Issue: I am facing a problem with the breadcrumbs component in my project, which is utilizing file explorer functionality from this specific project. The issue at hand is related to changing the disk being displayed by the component. Upon clicking on any ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...

How to Invoke JavaScript Functions within jQuery Functions?

I'm working on a jQuery function that involves dynamically loading images and checking their width. I have two JavaScript functions, func1() and func2(), that I want to call from within the jQuery function in order to check the width of each image. T ...

Detecting the end of a node

Can a node script determine whether it was terminated by an "external" force (e.g. kill) or internally due to a script error? To clarify: In the first scenario, it should not be the main process monitoring its children or an additional script checking if ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

Guide to removing a duplicate footer generated by a Rails application due to the use of .load in jQuery/AJAX

Currently, I am utilizing jQuery/AJAX to dynamically load a page within my rails application using the code snippet shown below: $("#div1").load(url); The challenge I am facing is that the loaded page contains its own footer. As a result, when this div i ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Issue: nodebuffer is incompatible with this platform

Currently, I am attempting to utilize the Shpjs package in order to import a Shape file onto a Leaflet map. According to the Shpjs documentation: shpjs Below is the code snippet I am working with: const [geoData, setGeoData] = useState(null); //stat ...

Improved Node.js algorithm designed to identify anagrams of a specific string in an array. The approach must not rely on generating all possible subsets to find the anagram of the string

I am looking to create a collection of anagram pairs within an array. The input will consist of the initial array of strings. For example: let inputArray = ["abcd", "dbac", "adfs", "adsf", "bDca"]; This program should consider the case of the letters, m ...

Initiate an Ajax request solely for the elements currently visible on the screen

I am currently facing an issue that requires a solution. Within our template, there are multiple divs generated with the same classes. Each div contains a hidden input field with the ID of the linked target site. My task is to utilize this ID to make aja ...

I have some questions regarding the process of adding documents to MongoDB using the native driver in Node

Encountering challenges when working with write concerns in the mongodb native driver for Node.js. Utilizing a single MongoDB server on localhost. Below is the code snippet being used: function insertNewDoc(newdoc, cbsuccess, cberror){ db.collection(&apo ...

Enhance user experience by implementing an interactive feature that displays

I have a form for adding recipes, where there is an ingredients button. Each recipe can have multiple ingredients. When the button is clicked, an input field for adding ingredients should appear below the ingredient button. What I've attempted so far ...

Create an Express application that features a single API route designed to accept a fullName as a query parameter. The API will then split the fullName into firstName

When accessing the route /name, fullName is expected as a query parameter and the output should include firstName and lastName. app.get('/name', (req, res) => { const { fullName } = req.query; let firstName = fullName.split(" ").sli ...

Transfer information via ajax to yii controller

Thank you all for your assistance, it has been incredibly helpful. I am new to yii and feeling a bit overwhelmed at the moment. I have created a jQuery script to validate a form and then send it to my controller to process and save in the database. Howev ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

Why does the same error keep popping up every time I attempt to install my React application?

I am new to React and feeling frustrated as I keep encountering the same error repeatedly. I have tried three different codes individually: npx create-react-app myapp npm init react-app myapp npm install -g create-react-app followed by create-react- ...