2016-06-08 121 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那樣可以更好地解釋回調。