2016-06-08 85 views
0

我需要找到一种方式返回一个字符串来消化我的主代码块以及一个回调或开始处理我的主代码块中的其余代码一旦值摘要被返回。NodeJS回调和返回值混淆

请帮忙!

这是我目前的代码不起作用。

var digest = checkIntegrity(filePath, res[3]); 
//digest always come back undefined and never matches res[2] so file always deletes 

if (digest === 0){ 
    console.log('File Inaccessible'); 
} else { 
    if (digest === res[2]){ 
     createNewFile(); 
    } else { 
     console.log('File hash doesn't match'); 
     delBadFile(); 
    } 
} 

function checkIntegrity(filePath, algorithm, cb){ 
    console.log('in checkIntegrity'); 
    var hash = crypto.createHash(algorithm); 
    var digest; 

    //see if file is there 
    fs.stat(filePath, function(fileErr, fileStats){ 
     if(fileErr){ 
      //error accessing file, most likely file does not exist 
      return 0; 
     } else { 
      //file exists 
      var fileIn = fs.createReadStream(filePath); 
      fileIn.on('data', function(chunk){ 
       if (chunk) { 
        hash.update(chunk); 
       } 
      }); 

      fileIn.on('end', function(){ 
       return hash.digest('hex'); 
      }); 
     } 
    }); 
} 

回答

2

你是checkIntegrity函数是异步的,即它接受回调。您希望作为该函数结果传递的任何值应作为参数传递给该回调函数。在你的例子中发生的是checkIntegrity调用fs.stat(它也是异步的),然后直接返回undefined - 在fs.stat有机会完成之前。

你有一个选择:

  1. 改变呼叫从fs.statfs.statSync。这是stat函数的同步版本。
  2. 更改您的代码以正确使用回调:

    checkIntegrity(filePath, res[3], function (err, digest) { 
        if (err) return console.error(err); 
    
        if (digest === 0) { 
         console.log('File Inaccessible'); 
        } else { 
         if (digest === res[2]){ 
          createNewFile(); 
         } else { 
          console.log('File hash doesn\'t match'); 
          delBadFile(); 
         } 
        } 
    }); 
    
    function checkIntegrity(filePath, algorithm, cb){ 
        console.log('in checkIntegrity'); 
        var hash = crypto.createHash(algorithm); 
        var digest; 
    
        //see if file is there 
        fs.stat(filePath, function(fileErr, fileStats) { 
         if(fileErr){ 
          //error accessing file, most likely file does not exist 
          return cb(fileErr); 
         } else { 
          //file exists 
          var fileIn = fs.createReadStream(filePath); 
          fileIn.on('data', function(chunk){ 
           if (chunk) { 
            hash.update(chunk); 
           } 
          }); 
    
          fileIn.on('end', function() { 
           cb(null, hash.digest('hes')); 
          }); 
         } 
        }); 
    } 
    

在我看来,异步代码和回调Node.js的是这样一个基本的部分,我会鼓励你去选择2。绝对值得学习。有数百个网站像callbackhell.com那样可以更好地解释回调。