等待this.fs.copyTpl在Yeoman Generator上完成

时间:2018-10-03 14:48:49

标签: yeoman yeoman-generator

我的Yeoman Generator中包含以下代码:

_appTemplate(src, dest, addToHG, scope) {
  let done = this.async();
  if (src === null || dest === null) {
    return;
  }

  let fullPathSrc = this.templatePath(src);
  let fullPathDest = this.destinationPath(path.join('src', dest));
  this.fs.copyTpl(fullPathSrc, fullPathDest, scope);

  if (addToHG) {
    this.log('Adding:' + fullPathDest + ' to HG now...');
    this.spawnCommand('hg', ['add', fullPathDest]).on('close', done);
  } else {
    done();
  }
}

但是我看到尝试将文件添加到HG(水银)中的尝试太早了,文件不存在。我要如何等到copyTpl完成?

我尝试了以下操作,但均未成功:

this.fs.copyTpl(fullPathSrc, fullPathDest, scope).then(() => {});

this.fs.copyTpl(fullPathSrc, fullPathDest, scope).on('end', () => {});

但是似乎支持下位模式,我找不到此的实际文档。fs.copyTpl()。

谢谢!

2 个答案:

答案 0 :(得分:0)

当然,在发布我的问题几分钟后,我找到了this.fs.copyTpl()的文档。原来这是一个“内存中”文件系统程序包,直到以后才将文件提交到磁盘。

https://github.com/SBoudrias/mem-fs-editor#copyfrom-to-options

这是一个可行的解决方案,但我不知道它是否理想。我愿意在这里提出建议。

_appTemplate(src, dest, addToHG, scope) {
  let done = this.async();
  if (src === null || dest === null) {
    return;
  }

  let fullPathSrc = this.templatePath(src);
  let fullPathDest = this.destinationPath(path.join('src', dest));

  this.fs.copyTpl(fullPathSrc, fullPathDest, scope);
  this.fs.commit([], () => {
    if (addToHG) {
      this.log('Adding:' + fullPathDest + ' to HG now...');
      this.spawnCommand('hg', ['add', fullPathDest]).on('close', done);
    } else {
      done();
    }
  });
}

答案 1 :(得分:0)

我正在做一些相关的事情。

我没有足够的声誉来发表评论。所以我写一个答案,那根本不是答案:

如果我使用this.fs.commit,则所有内容都会提交,并且不会询问用户是否覆盖文件。使用mem-fs-editor的原因是我们要提示用户是否覆盖的问题。

您找到其他方法了吗? 我继续搜索,但尚未找到解决方案:

mem-fs-editormem-fs之上。 mem-fs存储区继承自EventEmitter,并发出change事件。 参见SBoudrias/mem-fs/blob/master/index.js

// ...

// line 28
var Store = function () {
    events.EventEmitter.apply(this, arguments);
};
util.inherits(Store, events.EventEmitter);

// ...

// Line 38
Store.prototype.add = function (file) {
    store[file.path] = file;
    this.emit('change');
    return this;
};


// ...

可能是change事件可能有用。但是不幸的是,没有参数传递给监听器函数。所以我们不知道发生了什么变化。

this.fs.store.on( 'change', () => {
    console.log( 'Something has changed. But who knows what?' );    
} );

要查看存储中的所有文件:this.fs.store.each( file => console.log( file ) );

也许可以添加侦听器功能,运行this.fs.copyTpl并再次删除侦听器。

希望对某人有帮助。