I am new to Javascript and having a problem. In my script I want to get the last file that was added to a folder. This works fine, but when I want to use that name of the file afterwards it doesn't work. Because on the console I can see that the script did not execute in sequence I would expect.
var fs = require('fs');
var direc = path.join(__dirname, '../', 'uploads');
var url = 'start';
console.log('1');
fs.readdir(direc, function(err, list){
list.forEach(function(file){
current = fs.statSync(direc + '/' + file).ctime;
if (current > temp ){
url = file;
console.log('2');
}
temp = fs.statSync(direc + '/' + file).ctime;
})
console.log('3');
});
console.log(url);
console.log('4');
And the result in the console is:
1
start
4
3
2
Why doesnt javascript execute in a way that you would predict, meaning from 1-->2-->3-->url-->4?