【问题标题】:yeoman can't edit XML file that was created by other sub generatoryeoman 无法编辑由其他子生成器创建的 XML 文件
【发布时间】:2015-10-22 15:59:31
【问题描述】:

我正在尝试在一个子生成器中更改由另一个生成器创建的 XML 文件。

我的主生成器会进行提示并确定应该使用哪些子生成器。简而言之,它看起来像这样:

var MainGenerator = module.exports = yeoman.generators.Base.extend({
  writing: function () {
    this.composeWith('design:setup', {});
    if (this.option.get('someOption')) {
      this.composeWith('design:extend', {});
    }
  }
});

设置生成器添加了一些用于设计的每个变体的文件。例如一个项目 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 语句。

【问题讨论】:

  • 问题仍然是如何编辑 xml。但以防万一有人在 google 中发现:我已经更改了架构,因此不必更改 xml 文件。现在子生成器将需要在 xml 中注册的文件注册到一个数组中,主生成器像往常一样使用 this.fs.copyTpl() 将它们全部写入文件

标签: xml node.js xml-parsing yeoman fs


【解决方案1】:

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

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

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

【讨论】:

  • 感谢亚当,这可能会派上用场。我已经更改了我的生成器,因此它首先收集所有需要的数据,然后将其写入代码中一个中心点的 xml 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多