错误:无法读取属性' forEach'未定义的

时间:2017-07-26 08:02:30

标签: javascript node.js

我尝试读取未格式化的文档,然后以良好的格式重写它 当我执行以下代码时,我收到错误Cannot read property 'forEach' of undefined(下面的完整错误)。 我不明白为什么会发生这种错误以及如何解决它。

CODE

const testFolder = '/zip_file\ /sit1_Wave2_Settlement_afx_formula\ \(1\)/data_dictionary/CM.173/';

var fs = require('fs');
var formatedcode = [];
fs.readdir(testFolder, (err, files) => {

    files.forEach(file => {
      console.log(file);
      var array = fs.readFileSync(testFolder + file).toString().split("\n");
      //console.log("\n\n\n",array);
      var wstream = fs.createWriteStream(file);

      for (i in array) {
        var xml = array[i],
        pp_xml = require('../pretty-data').pd.xml(xml);
        formatedcode.push(pp_xml);
      }

      for (look in formatedcode) {
        var wstream = fs.createWriteStream(file);

        wstream.on('finish', function () {
          console.log('file has been written');
        });

        wstream.write(formatedcode[look]);
        wstream.end();
      }
  });
})

错误

files.forEach(file => {^

TypeError: Cannot read property 'forEach' of undefined
  at fs.readdir (C:\Users\Manoj kumar\Downloads\pretty-data\pretty-data\findingxml.js:5:6)
  at FSReqWrap.oncomplete (fs.js:123:15)

1 个答案:

答案 0 :(得分:0)

我对您的代码进行了一些修改。还有一些其他的事情你需要注意,比如wstream被多次定义,这可能会导致意想不到的结果。

关于您的问题,请尝试以下操作;

files.forEach((file) => 
{
    console.log(file);

为方便起见,请查看完整的代码块;

const testFolder = '/zip_file\ /sit1_Wave2_Settlement_afx_formula\ \(1\)/data_dictionary/CM.173/';

var fs = require('fs');
var formatedcode = [];
fs.readdir(testFolder, (err, files) => {

    files.forEach((file) => 
    {
        console.log(file);

        var array = fs.readFileSync(testFolder + file).toString().split("\n");
        //console.log("\n\n\n",array);

        var wstream = fs.createWriteStream(file);
        for (var i in array) {
            var xml = array[i],

                pp_xml = require('../pretty-data').pd.xml(xml);
            formatedcode.push(pp_xml);

        }
        for (var look in formatedcode) {
            wstream = fs.createWriteStream(file);
            wstream.on('finish', function () {
                console.log('file has been written');
            });
            wstream.write(formatedcode[look]);
            wstream.end();
        }
    });
});