0

i get this error "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when i wanna send content of files to client.

const testFolder = './uploads/';
* app.get('/filedata',function(req,res){
 fs.readdir(testFolder, (err, files) => {
   files.forEach(file => {
      fs.readFile( testFolder+file,'utf8',(err,data)=>{
        if (err) {
          console.log(err);



      }
      console.log(data);
         res.json(data);


      });

    });
  });




  });
msh65
  • 13
  • 5
  • My guess is that res.json completes a json response. The first call to that probably succeeds; it's when you go to the next file in the forEach that it tries to call res.json again, but you've already sent a response in the first iteration of the forEach loop. Try setting a let response_obj = {}; outside the forEach. In every iteration, add to that ( response_obj = { ...response_obj, ...data }; ). Then once you've finished the forEach loop, res.json(response_obj); – dmitrydwhite Dec 28 '19 at 08:00
  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – TGrif Dec 28 '19 at 08:22

1 Answers1

0

The reason you're getting "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" error is because you're sending back response as soon as you're reading the very first file, and so when you try to send back second file, you get the error that you cannot set headers after they are sent to the client, i.e. response is already served. Refer this for more details.

One possible approach to solve this issue is to use readFileSync to read all files, store them in an object and after all files are read successfully, send them back as response. Like this,

const testFolder = './uploads/';
app.get('/filedata',function(req,res){
    fs.readdir(testFolder, (err, files) => {
        let allData = {}
        files.forEach(file => {
            let data = "";
            try{
                // Use readFileSync instead of readFile to avoid handling promises and read synchronously
                data = fs.readFileSync(testFolder+file).toString() // Read data and convert to string
            }catch(err){
                console.log(err); // Any error
            }
            allData[file] = data; // Add to all data object with key as filename and value as data string
        });
        res.json(allData); // Send all data
    });
});
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15