2015-10-11 142 views
2

我试图将名称与来自特定目录的所有文件的路径一起散列。散列之后,我将散列保存到数组(hash_orig)中。这是我所做的。无法访问函数外部的数组元素

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) 

问题:

的问题是,当我推散入hash_orig阵列,并试图访问它的功能fs.readdir数组hash_orig外面是空的。 (console.log(hash_orig)

我需要在外部访问它以执行进一步的比较操作,以确定散列是否已更改为验证文件名和路径的完整性。 我做错了什么? 谢谢。

回答

0

是的,你只是想念你的fs.readdir函数是一个异步回调。

因此,当您从外部拨打console.log(hash_orig)时,实际上回调尚未完成。

使用超时,你的阵列将填充:

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

fs.readdir是一个异步函数。当达到console.log(hash_orig)时,readdir的回调尚未调用。 将日志语句放在回调结束处,您将看到结果。

+1

或者使用'readdirSync' – brandonscript