Chris
Chris

Reputation: 944

Cant access array elements outside a function

I am trying to hash the name together with the path of all the files from a specific directory. After hashing I am saving the hash into the array(hash_orig). Here is what I have done.

var fs = require('fs');
var Hashes = require('jshashes');
var path = process.argv[2];
var path_elements = new Array();
var hash_orig = new Array();


fs.readdir(path, function(err, items) {
console.log('\nNumber of files in the directory: '+items.length);
console.log('Hashing algorithm: SHA1')
    for (var i=0; i<items.length; i++) {
        path_elements.push(path+"/"+items[i])
        var SHA1 = new Hashes.SHA1().b64(path_elements[i])
        console.log([i+1]+':\t'+items[i]+"\t" + SHA1)
        hash_orig.push(SHA1);
    }
});

    console.log(hash_orig)

The problem:

The problem is that when I am pushing the hash into the hash_orig array and trying to access it outside the function fs.readdir the array hash_orig is empty. (console.log(hash_orig))

I need to access it outside in order to perform further some comparison operation to determine if the hash has been changed to Verifying Integrity of the files name and path. What I am doing wrong? Thank you.

Upvotes: 2

Views: 198

Answers (2)

R&#233;mi Becheras
R&#233;mi Becheras

Reputation: 15222

Yes you are simply missing that your fs.readdir function is a asynchronous callback.

Thus, when you call console.log(hash_orig), from outside, in fact the callback isnt completed yet.

Use a timeout and your array will filled :

setTimeout(function(){
  console.log(hash_orig);
},500);

Upvotes: 1

PatrickD
PatrickD

Reputation: 1156

fs.readdiris a async function. At the time when console.log(hash_orig)is reached, the callback of readdir is not called yet. Put the log-statement at the end of your callback and you will see the results.

Upvotes: 4

Related Questions