简体   繁体   中英

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);

});
})

I need to read a file contents, if i execute the above code it shows an error.

files.forEach(function(file) {
   ^

TypeError: Cannot read property 'forEach' of undefined

You should check for errors before trying to read the files, and then check to see if the files object is defined, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM