作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我需要逐行读取文件,并相应地更改变量。我通常会用 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
.
雇佣兵。
最佳答案
库返回的 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);
});
}
});
[编辑] 回答有关我如何找到此信息的问题:
我确实查看了the source file for the project ;我知道该库有一个 sum
方法,可以链接到 Lazy 的实例以在最后总结所有内容; code for that method调用 foldr
,以及 code for that method监听名为 pipeName
的事件,默认为 in line 22作为管道
。
关于javascript - Node 和惰性 : How do I know when it's done?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11118169/
我是一名优秀的程序员,十分优秀!