【问题标题】:Stop stream read of fast-csv node module停止 fast-csv 节点模块的流读取
【发布时间】:2016-12-10 13:08:48
【问题描述】:

如何使用 fast-csv 节点模块停止读取某个特定索引处的 csv 行?在 fast-csv 中,它们是流暂停和恢复的选项,但没有在某些特定行关闭流的选项。 以下是代码:

var csvstream = CSV
.fromPath(self.fetchFilePath(fileName),{ ltrim : true, rtrim : true , headers : true , ignoreEmpty : true })
.transform(function (data){
    Object.keys(data).forEach(function (key) {
       var newKey       = key.trim();
       data[newKey]     = data[key].trim();
    });
    return data;
})
.on("data", function(data){
     //checking unicode char presence
     Object.keys(data).forEach(function (key) {
       if(data[key]){
          var charValue   = PUNYCODE.ucs2.decode(data[key]);
          charValue = charValue.map(function(val) {
             if(val>126){
               FileCleanFlag=false;
               errorData.push(data);
             }
          });
       }else{
          FileCleanFlag=false;
       }
     });

     if(!FileCleanFlag){
        #here want to jump to end block instead of parsing next rows
     }
})
.on('end', function (){
    #some work on rows containing error
});

在上面的代码中,如果某行发生错误,我如何跳转到“结束”块?

【问题讨论】:

  • 欢迎来到 StackOverflow!我建议你分享你已经做过的事情(例如你的代码)——那时人们会更有可能帮助你
  • @deeveeABC : 添加代码示例
  • 有人帮忙吗?

标签: node.js csv


【解决方案1】:

没有很好的方法来结束流。您可以将 FileCleanFlag 定义为 true,然后如果它的 false 不再起作用。

var FileCleanFlag = true;
var csvstream = CSV
.fromPath(self.fetchFilePath(fileName),{ ltrim : true, rtrim : true , headers : true , ignoreEmpty : true })
.transform(function (data){
Object.keys(data).forEach(function (key) {
   var newKey       = key.trim();
   data[newKey]     = data[key].trim();
});
    return data;
})
.on("data", function(data){
     if (!FileCleanFlag) { return; }
     //checking unicode char presence
     Object.keys(data).forEach(function (key) {
     if(data[key]){
      var charValue   = PUNYCODE.ucs2.decode(data[key]);
      charValue = charValue.map(function(val) {
         if(val>126){
           FileCleanFlag=false;
           errorData.push(data);
         }
      });
   }else{
      FileCleanFlag=false;
   }
 });

 if(!FileCleanFlag){
    #here want to jump to end block instead of parsing next rows
 }
})
.on('end', function (){
   #some work on rows containing error
});

如果您需要走这条路,请参阅How to close a readable stream (before end)? 了解如何关闭流黑客。

您也可以抛出错误并相应地捕获它。

【讨论】:

  • 那么我们可以使用 stream.destroy() 和 fast-csv 以便控制转到 on.('close') 块吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 2019-06-22
  • 2017-08-16
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多