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

编程入门 行业动态 更新时间:2024-10-16 00:26:32

无法读取未定义nodejs的<a href=https://www.elefans.com/category/jswz/34/1771415.html style=属性'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);
    });
  }
});

更多推荐

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

本文发布于:2024-05-07 06:47:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   未定义   forEach   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!