我需要逐行读取文件,并相应地更改变量。我通常会用 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
.
默克。