0

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?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
j0k3r87
  • 43
  • 6

2 Answers2

1

That's because you're performing an asynchronous operation. Instead of waiting for the response, the execution continues immediately and the statement after the request call is execute.

You can fix this using a callback function.

function read(callback){
   fs.readdir(direc, function(err, list){ 
      list.forEach(function(file){
         current = fs.statSync(direc + '/' + file).ctime;
         if (current > temp ){
           url = file;
         }
         temp = fs.statSync(direc + '/' + file).ctime;
      })
      callback(url);
    });
}

read(function(url){
     console.log(url); 
});

Here are possible approaches in order to solve your problem.

  • Promises with async/await (ES2017+)
  • Callbacks
  • Promises with then() (ES2015+)
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • Thank you for your comment. However, when I use the code you supplied the console only says '1' and then the page goes into a loop for minutes. And which one your suggested approcaches would you choose to solve the problem? – j0k3r87 Jan 12 '18 at 12:07
-1

It happens because JavaScript's fs.readdir function is asynchronous. It means it does not guarantee that it will be called in the same order you have it in your code.

You might want to take a look at:

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Max Larionov
  • 420
  • 6
  • 19