2017-04-17 225 views
0

現在我有一個模塊有兩種方法。如何訪問downloadFile函數以在downloadFiles函數中重用。現在它會拋出downloadFile沒有定義的異常。提前致謝。從另一個功能模塊訪問功能

exports.downloadLib = { 
    downloadFile: async function (fileUrl, dest) { 
     const shell = require('node-powershell'); 

     let ps = new shell({ 
      executionPolicy: 'Bypass', 
      noProfile: true 
     }); 

     let commandString = `iwr ${fileUrl} -OutFile ${dest}`; 
     ps.addCommand(commandString); 

     try { 
      await ps.invoke(); 
     } catch (e) { 
      console.log(`ERROR - ${e}`); 
     } finally { 
      await ps.dispose(); 
      console.log(`finished download file ${dest}`) 
     } 
    }, 

    downloadFiles: function (fileUrls) { 
     fileUrls.forEach(function (fileUrl) { 
      downloadFile(fileUrl, fileUrl.substring(fileUrl.lastIndexOf('/') + 1)) 
     }, this); 
    } 
}  
+2

this.downloadFile –

+0

您可以在'downloadFiles'內使用'this.downloadFile'。 –

回答

1

爲模塊創建一個私有方法。另外,將其注入到模塊中,並在需要的地方調用它。下劃線前綴是許多人用來表示私有方法的慣例。

async function _downloadFile(fileUrl, dest) { 
 
    const shell = require('node-powershell'); 
 

 
    let ps = new shell({ 
 
    executionPolicy: 'Bypass', 
 
    noProfile: true 
 
    }); 
 

 
    let commandString = `iwr ${fileUrl} -OutFile ${dest}`; 
 
    ps.addCommand(commandString); 
 

 
    try { 
 
    await ps.invoke(); 
 
    } catch (e) { 
 
    console.log(`ERROR - ${e}`); 
 
    } finally { 
 
    await ps.dispose(); 
 
    console.log(`finished download file ${dest}`) 
 
    } 
 
} 
 

 
exports.downloadLib = { 
 
    downloadFile: _downloadFile, 
 

 
    downloadFiles: function(fileUrls) { 
 
    fileUrls.forEach(function(fileUrl) { 
 
     _downloadFile(fileUrl, fileUrl.substring(fileUrl.lastIndexOf('/') + 1)) 
 
    }, this); 
 
    } 
 
}

您也可以保留_downloadFile()模塊內部,這樣做this._downloadFile()context._downloadFile()。您需要在模塊的頂部爲後者定義let context = this

+0

但是爲什麼?我沒有看到這樣做的原因... –

+0

容易改變,無論你是否出口_downloadFile –

+0

讓我承認你的答案更簡單。我只是給出了我所知道的答案,並沒有說它是完美的。嗯,我也避免'這個',以防開發商對此產生反感。 –

0
downloadFiles: function (fileUrls) { 
    fileUrls.forEach(function (fileUrl) { 
     this.downloadFile(fileUrl, fileUrl.substring(fileUrl.lastIndexOf('/') + 1)) 
    }, this); 
} 

downloadFile不是downloadFiles範圍的一部分,而是其上下文。

+0

這種方式不適用。這種方式的背景是全球性的客體。 –

+0

@Jordan Kanchelov是。看起來你不知道forEachs第二參數...提示:這不是全球... –

+0

如果我使用'嚴格使用'「這個」在這種情況下是不確定的。在這種情況下,當我不使用它應該指向全球? –