簡體   English   中英

files.forEach(function(file){^ TypeError:無法讀取未定義的屬性'forEach'

[英]files.forEach(function(file) { ^ TypeError: Cannot read property 'forEach' of undefined

var testFolder = '/zip_file\ /sit1_Wave2_Settlement_afx_formula\ \
(1\)/data_dictionary/CM.173/';
   var fs = require('fs');
      fs.readdir(testFolder, (err, files) => {
        files.forEach(file => {
    console.log(file);

});
})

我需要讀取文件內容,如果我執行上述代碼,則會顯示錯誤。

files.forEach(function(file) {
   ^

TypeError: Cannot read property 'forEach' of undefined

在嘗試讀取文件之前,應檢查錯誤,然后檢查是否定義了files對象,如下所示:

fs.readdir(testFolder, (err, files) => {
    if (err) throw err;
    if (files){
        files.forEach(file => {
            console.log(file);
        });
    } else {
        console.log('no files found')
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM