最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法读取未定义nodejs的属性'forEach'

网站源码admin9浏览0评论

无法读取未定义nodejs的属性'forEach'

无法读取未定义nodejs的属性'forEach'

看到了几个与此主题相关的主题,但无法掌握针对我的特定用例的解决方案。在下面的示例中,无法读取.forEach。出于什么原因会发生这种情况?

const coi = './categories';
const fs = require('fs');

fs.readdir(coi, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});
d:\sw_lbi\index.js:6
  files.forEach(file => {
        ^

TypeError: Cannot read property 'forEach' of undefined
    at d:\sw_lbi\index.js:6:9
    at FSReqCallback.oncomplete (fs.js:163:23)

更新

此错误与forEach无关。

回答如下:

这几乎可以肯定是因为readdir报告了一个错误。 err将被设置为某些值。您应该对其进行测试,至少要看看它是什么,也许从一条日志消息开始。也许目录不存在?

const coi = './categories';
const fs = require('fs');

fs.readdir(coi, (err, files) => {
  if (err) {
    console.error(err);
    // deal with it as you see fit
  } else {
    files.forEach(file => {
      console.log(file);
    });
  }
});
发布评论

评论列表(0)

  1. 暂无评论