检查目标文件是否已存在

Checking if destination file already exists

本文关键字:存在 是否 文件 目标 检查      更新时间:2023-09-26

>Goal

检查两个文件夹(src 和目标文件夹)中是否存在同名文件

尝试尝试使用grunt-contrib-copy遍历路径,但显然这不起作用。

copy: {
  unit: {
    expand: true,
    cwd: 'src',
    src: '**',
    dest: 'specs/unit',
    filter: function(filepath){
      if(grunt.file.exists(filepath)){
        return grunt.file.write(filepath,'');
      }
    }
  }
},

我的理论

grunt.file.exists似乎指向 src 文件夹而不是目标文件夹。因此,它从不检查src文件夹中的文件是否实际存在于目标文件夹中,它只是检查src文件夹中是否有任何文件。

您可以随时使用 fs.existsSync() : http://nodejs.org/api/fs.html#fs_fs_exists_path_callback。一定要使用同步的,Grunt 不喜欢异步函数。

另外;确保返回布尔值。

Gruntfile.js的顶部:

var fs = require('fs');

在您的任务设置中;

copy: {
  unit: {
    expand: true,
    cwd: 'src',
    src: '**',
    dest: 'specs/unit',
    filter: function(filepath){
      return !fs.existsSync(filepath);
    }
  }
},

grunt.file.setBase('./destination')

检查文件

grunt.file.setBase('./src')

检查文件