4

我需要逐行读取文件,并相应地更改变量。我通常会用 PHP 编写这个......但我决定接受挑战。

我写:

fs = require('fs');
Lazy = require('lazy');
path = require('path');

files = fs.readdirSync('.');
var software = {};


files.forEach( function(fileName){


  var m; 
  if( m = fileName.match(/^(.*)\.txt$/) ){
    name = m[1];

    console.log("Processing file: " + fileName);
    software[name] = {};
    console.log("Software 1: %j",software);

    var section = 'unset';
    new Lazy(fs.createReadStream(fileName)).lines.forEach(
      function(line){
        var m;
        line = line + '';
        if( m = line.match(/^([a-zA-Z_]*):$/)){
          section = m[1];
          software[name][section] = '';
          console.log("Switching to section " + m[1]);
          console.log("Software 2: %j",software);
        } else if (line == '.'){
          section = 'unset'
        } else if (line == ''){
          section = 'unset'
        } else { 
          console.log("LINE: " + line) ;
          software[name][section] = software[name][section] + line + "\n";
          console.log("Software 3: %j",software);
        }
      }

    );   
  }

});

console.log("Software 4: %j",software);

除了代码非常丑陋且未优化之外,我遇到了问题,因为当最后一行打印时,“软件”变量尚未填充!我猜 Lazy 是异步的。所以,它基本上可以工作,但“在以后的某个时候”。这很好,但是......当填充软件变量的重要循环实际上完成时,我在哪里编写代码?!?

根据要求:要玩的数据!

只需创建“something.txt”并编写:

name:
Name 1
.

Option 1:
Value 1
.

Option 2:
Value 2
.

Option 3:
Multi
Line
Value
.

Another_section:
Again
.

默克。

4

1 回答 1

15

库返回的 Lazy 实例是EventEmitters,它会pipe在“一组”操作完成时发出调用的事件:

new Lazy(
  ...
).on('pipe', function() {
  // all done
});

修改代码以使用此事件会导致(唯一的更改在底部附近):

fs = require('fs');
Lazy = require('lazy');
path = require('path');

files = fs.readdirSync('.');
var software = {};


files.forEach( function(fileName){


  var m;
  if( m = fileName.match(/^(.*)\.txt$/) ){
    name = m[1];

    console.log("Processing file: " + fileName);
    software[name] = {};
    console.log("Software 1: %j",software);

    var section = 'unset';
    new Lazy(fs.createReadStream(fileName)).lines.forEach(
      function(line){
        var m;
        line = line + '';
        if( m = line.match(/^([a-zA-Z_]*):$/)){
          section = m[1];
          software[name][section] = '';
          console.log("Switching to section " + m[1]);
          console.log("Software 2: %j",software);
        } else if (line == '.'){
          section = 'unset'
        } else if (line == ''){
          section = 'unset'
        } else {
          console.log("LINE: " + line) ;
          software[name][section] = software[name][section] + line + "\n";
          console.log("Software 3: %j",software);
        }
      }

    ).on('pipe', function() {
      console.log("Software 4: %j",software);
    });
  }

});

[编辑]要回答您有关我如何找到此信息的问题:

我确实检查了项目的源文件;我知道图书馆有一种sum方法可以链接到 Lazy 的实例,以便在最后总结所有内容;该方法调用foldr代码,该方法的代码侦听一个被调用的事件,在第 22 行pipeName默认为.pipe

于 2012-06-20T11:30:19.027 回答