Search code examples
javascriptjquerynode.jsfilesystems

Uncaught ReferenceError: date is not defined | JavaScript NodeJs jQuery FileSystem


I was testing some stuff with JavaScript and nodejs. I wanted to ask the user a folder and it would show the name of the files in folder, the type of file (executable, text file...) and the changed date (when the file was changed or modified last time). The code below:

fs.stat(testFolder, (err, stats) => {
    var time = stats.ctime
    var day = time.getDay()
    var month = time.getMonth()
    var year = time.getFullYear()
    var date = day + " " + month + " " + year
})
const testFolder = './tests/'
const fs = require('fs')
fs.readdir(testFolder, (err, files) => {

    files.forEach(file => {
        var tmp = file.split(".")
        var name = tmp[0]
        var kind = kinds[tmp[1]]
        if(kind == null) {
            kind = "File"
        }
        $( "#test" ).append( "<tr class=\"file\">\
              <td>" + name + "</td>\
              <td>" + kind + "</td>\
              <td>" + date + "</td>\
            </tr>" );
    });
})

I have the variable time which holds the full date. And when I use console.log(date) it works.

console.log(date)

But when I try and add the date variable to the append method with jQuery it gives me an error:

enter image description here


Solution

  • You define and set your date-variable in an asynchronous function. There is no guarantee that the callback is run before your readdir-callback runs. Move the readdir-call into the fs.stat callback.

     const testFolder = './tests/';
     const fs = require('fs');
     fs.stat(testFolder, (err, stats) => {
       var time = stats.ctime;
       var day = time.getDay();
       var month = time.getMonth();
       var year = time.getFullYear();
       var date = day + " " + month + " " + year;
    
    
       fs.readdir(testFolder, (err, files) => {
         files.forEach(file => {
           var tmp = file.split(".");
           var name = tmp[0];
           var kind = kinds[tmp[1]];
           if(kind == null) {
             kind = "File";
           }
           $( "#test" ).append( "<tr class=\"file\">\
                       <td>" + name + "</td>\
                       <td>" + kind + "</td>\
                       <td>" + date + "</td>\
                     </tr>" );
         });
       });
     });