强制覆盖文件

Force overwrite file

我在我的生成器中使用它

this.fs.copy(this.templatePath('index.html'),this.destinationPath('index.html') );

我希望它在每次发现冲突时跳过覆盖确认(例如强制覆盖选项)

这是不可能的。 Yeoman 在覆盖文件之前总是会要求用户确认。这是该工具与其用户签订的合同:未经用户确认,它不会覆盖文件。

作为用户,如果您信任您的生成器,您可以 运行 它带有 --force 标志以自动覆盖冲突文件。

如果必须这样做,您仍然可以 force 使用 fs 中的 fs.copyFile(), fs.writeFile() or fs.writeFileSync() 函数覆盖文件。这两个函数都将数据写入文件,如果文件已经存在则替换该文件。

const yosay = require("yosay");

....

fs.writeFile(filePath, fileContent, 'utf8', err => yosay(err)); 

如果出现错误 File already exists,您可能需要在第三个参数中设置明确的 write 标志以使其工作:

fs.writeFile(filePath,fileContent,{encoding:'utf8',flag:'w'}, err => yosay(err));

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});