简体   繁体   中英

Error : Cannot read property 'forEach' of undefined

I try to read an unformatted document then rewrite it in a good format but when I execute the following code I got an error Cannot read property 'forEach' of undefined (full error below). I don't understand why this error happening and how to resolve it.

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

ERROR

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)

I have done some modifications to your code. There are some other things that you need to be careful about like wstream is defined multiple times which may cause unexpected results.

Regarding your issue please try as below;

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

For convenience check out the full code block;

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

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