Node.js读取当前目录中的文本文件并进行验证

时间:2016-12-16 19:29:03

标签: node.js electron

这实际上是我上一个问题的答案......提供的代码对我有用。我需要做的就是保留一个文件计数器(全局),并在验证添加到数组(全局)后的读取中将其传递回渲染过程。

// Called from Render Process.

ipcMain.on('search-text-files', (event, arg) => {


  const fs = require('fs');
  const path = require('path');


  var txtArr = [];
  var fileName = '';
  var fCtr = 0;


  fs.readdir(__dirname+'/', function (err, items) {


    if (err) {
      throw err;
    }


    // loop through directory items

    for (var i=0; i<items.length; i++) {


      if (path.extname(items[i].toString() == '.txt') {


        fctr+=1;
        fileName = items[i].toString();         



        // read the file & validate


        fs.readfile(__dirname+'/'+fileName, (err, data) {


          if (err) {
            throw err;
          }

          var checkArr[];
          var curFile = '';

          checkArr = data.toString().split('\r');


          // access contents line by line

          for (var line=0; line<checkArr.length; line++) {


            ... perform some sort of validation

            ... assign curFile from contents



          }


          if (file is valid) {

            txtArr.push(curfile);


          }


          fCtr-=1;

          if (fCtr == 0) {

            event.sender.send('text-files-found', txtArr);

          }


        });


      }  


    } 


  });  


});

0 个答案:

没有答案