【问题标题】:Read files from directory and save to array of object从目录读取文件并保存到对象数组
【发布时间】:2021-05-22 07:23:51
【问题描述】:

我有一个员工税务档案的目录。每个文件都有一个文件名作为员工代码。我正在读取每个文件并提取一些组件并保存到一组员工对象中。

const readline = require('readline');
let empArr = [];

function readFiles(dirname) {
fs.readdir(dirname, async function (err,filenames) {

if(err) {
  return err;
}

for await (file of filenames) {
  const filePath = path.join(__dirname,directoryPath,file);
  const readStream =  fs.createReadStream(filePath);   
  const fileContent = readline.createInterface({
    input: readStream
  });    
 
  let employeeObj = {
    empId : '',
    TotalEarning:'',
    ProfessionalTax:0,
    GrossIncome:0,
    isDone:false
  };

  fileContent.on('line', function(line) {         
    if(!employeeObj.empId &&  line.includes("Employee:")) {    
      const empId = line.replace('Employee: ','').split(" ")[0];    
      employeeObj.empId = empId;
    }
    else if(line.includes('Total Earnings')) {
      const amount = line.replace(/[^0-9.]/g,'');      
      employeeObj.TotalEarning = amount;
    } 
    else if(line.includes('Profession Tax')) {        
      const amount = line.split(" ").pop() || 0;    
      employeeObj.ProfessionalTax = amount;
    } 
    else if(line.includes('Gross Income')) {
      const amount = line.replace(/[^0-9.]/g,'');      
      employeeObj.GrossIncome = amount ||0;
    } 
    else if(line.includes('finance department immediately')) {
      employeeObj.isDone =true;
      empArr.push(employeeObj);           
    }
  });

  fileContent.on('close', function() {
    fileContent.close();      
  });
  }    
 })
}

readFiles(directoryPath);

我无法获得 empArr。得到数组后,我需要保存到excel。这部分我将在获取员工对象数组后尝试。

【问题讨论】:

  • 有什么问题?您无法根据您添加的条件进行读取?或者还有其他错误吗?正在读取的文件,扩展名是什么?你得到正确的数据了吗?您是否检查了即将发生的内容,包括文件路径、文件名等?
  • 一条新闻是for await (file of filenames) 中的await 没有做任何事情。 await 只在等待承诺时做一些有用的事情。
  • 所以,这里的主要问题是您在 for 循环中启动了一堆异步操作,它们都并行运行,您无法知道它们何时完成.因此,您无法知道empArr 何时被完全填充,因此无法使用它。您正在使用的 readline 模块的接口完全是非阻塞和异步的。所以你运行你的for 循环,它设置了一堆readline 对象,然后你的for 循环结束,然后所有readline 开始触发它们的line 事件。同时,您的函数已经返回。
  • @ApoorvaChikara 正在读取文件,并且employeeObj 也是正确的。只是问题是它被添加到 empArr 之后我不确定在哪里返回 empArr
  • @jfriend00 是的,当没有文件要处理时,empArr 已满。当我在 for() 循环之外尝试 console.log(empArr) 时,我得到空数组。

标签: javascript node.js async-await readline


【解决方案1】:

在阅读了几篇关于闭包和承诺的文章后,我得到了它。以下代码适用于我,并向我发送已处理的员工数组。

const directoryPath = './tax/';

function readFiles(dirname) {
  fs.readdir(dirname, async function (err,filenames) {    
   if(err) {
     return err;
   }

  let promiseArr = filenames.map( file=> {
    return new Promise((resolve)=>{
      processFile(file, resolve)
    })
 });

 Promise.all(promiseArr).then((ret)=>console.log(ret));   
 })
}
 

function processFile(file, callback) {
     const filePath = path.join(__dirname,directoryPath,file);
     const readStream =  fs.createReadStream(filePath);   
     const fileContent = readline.createInterface({
      input: readStream
     });    
  
    let employeeObj = {
      empId : '',
      TotalEarning:'',
      ProfessionalTax:0,
      GrossIncome:0,
      isDone:false
    };

   fileContent.on('line', function(line) {         
    if(!employeeObj.empId &&  line.includes("Employee:")) {    
      const empId = line.replace('Employee: ','').split(" ")[0];    
      employeeObj.empId = empId;
    }
    else if(line.includes('Total Earnings')) {
      const amount = line.replace(/[^0-9.]/g,'');      
      employeeObj.TotalEarning = amount;
    } 
    else if(line.includes('Profession Tax')) {        
      const amount = line.split(" ").pop() || 0;    
      employeeObj.ProfessionalTax = amount;
    } 
    else if(line.includes('Gross Income')) {
      const amount = line.replace(/[^0-9.]/g,'');      
      employeeObj.GrossIncome = amount ||0;
    } 
    else if(line.includes('finance department immediately')) {
      employeeObj.isDone = true;   
      return callback(employeeObj);
    }
    
  });

  fileContent.on('close', function() {
    fileContent.close();      
  }); 
}

readFiles(directoryPath);

当然,代码可以进一步改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多