约曼可以';t编辑由其他子生成器创建的XML文件

约曼可以';t编辑由其他子生成器创建的XML文件,xml,node.js,xml-parsing,yeoman,fs,Xml,Node.js,Xml Parsing,Yeoman,Fs,我试图对另一个子生成器创建的子生成器中的XML文件进行更改 我的主生成器执行提示并确定应该使用哪些子生成器。简单地说,它是这样的: var MainGenerator = module.exports = yeoman.generators.Base.extend({ writing: function () { this.composeWith('design:setup', {}); if (this.option.get('someOption')) { t

我试图对另一个子生成器创建的子生成器中的XML文件进行更改

我的主生成器执行提示并确定应该使用哪些子生成器。简单地说,它是这样的:

var MainGenerator = module.exports = yeoman.generators.Base.extend({
  writing: function () {
    this.composeWith('design:setup', {});
    if (this.option.get('someOption')) {
      this.composeWith('design:extend', {});
    }
  }
});
“设置生成器”会添加一些在设计的每个变体中使用的文件。例如,project config.xml

var SetupGenerator = module.exports = yeoman.generators.Base.extend({
  default: function () {
    // ^ default: makes sure the vsSetup is run before the writing action
    //   of the other sub generators
    this.fs.copy(
      this.templatePath( 'project/_config.xml' ),
      this.destinationPath( 'project/config.xml' )
    );
});
现在,根据用户在提示中选择的设置,将执行不同的子生成器。每次向目标添加新文件夹时,都必须在安装生成器创建的config.xml中更新该文件夹

var xml2js = require('xml2js');
var MainGenerator = module.exports = yeoman.generators.Base.extend({
  writing: function () {
    var xmlParser = new xml2js.Parser();
    this.fs.read( 'project/config.xml', function (err, data) {
      console.log('read file');
      console.dir(err);
      console.dir(data);

      xmlParser.parseString(data, function (err, result) {
        console.log('parsed xml: ' + 'project/config.xml' );
        console.dir(result);
        console.dir(err);
      });
    });
  }
});
fs read根本没有输出。没有错误,什么都没有。 知道我做错了什么吗


因为有不同的扩展生成器组合,我希望每个生成器注册它所需的文件夹,而不是在原始xml文件中有一个无法维护的地狱般的
if-else
语句。

我没有找到太多关于文件系统发出的任何事件的文档,或者从
composeWith
函数,但您可以挂接到
end
事件,然后读取文件

this.composeWith('design:extend', {})
    .on('end', function () {
        console.log(this.fs.read('path/to/file'));
        // do your file manipulation here
    });

这不是最好的方法,因为它是在文件提交到磁盘后修改文件,而不是在内存编辑器中,但这至少是一个好的起点。

问题仍然在于如何编辑xml。但为了以防万一,一些人在谷歌发现了这一点:我已经改变了我的架构,所以我不必改变xml文件。现在,子生成器将需要在xml中注册的文件注册到一个数组中,然后主生成器像往常一样将它们全部写入该文件中。fs.copyTpl()感谢adam,这可能会在某个时候派上用场,因为我已经更改了生成器,所以它首先收集所有需要的数据,然后在代码的一个中心点将其写入xml文件。