I'm struggling to get some data sent to my view page. I think it is to do with the order the code is running. This is my code;
exports.home = (req, res) => {
let fileMessage = 'starting message';
const fileSys = 'public/data/';
const fileArray = [];
fs.readdirSync(fileSys, (err, files) => {
if (err) console.log(err);
else {
files.forEach((file) => {
if (path.extname(file) === '.csv') {
fileArray.push(file);
}
});
if (fileArray.length === 1) {
fileMessage = 'OK';
console.log(fileMessage);
}
if (fileArray.length > 1) {
fileMessage = 'loads';
console.log(fileMessage);
}
if (fileArray.length === 0) {
fileMessage = 'none';
console.log(fileMessage);
}
}
});
console.log('before render');
res.render('index', {
title: 'Admin',
fileMessage,
home: true
});
console.log('after render');
};
In this format I get the following output;
before render
after render
Where clearly the file read is not happening.
If I change to readdir() i get;
before render
after render
none
So the file read function is occurring and getting the correct value however the value passed into the view template is still 'starting message'
I can't work out how to get this in the correct order so that i can pass the fileMessage variable to my view file with either, OK, loads, none