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
});
});