javascriptnode.jsgruntjsgrunt-contrib-copy

Checking if destination file already exists


Goal

To check if a file with a same name exists in two folders (src and destination folder)

Attempt Tried using grunt-contrib-copy to traverse the path but obviously this is not working.

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

My Theory

grunt.file.exists seems to be pointing to the src folder instead of destination folder. So it never checks if the files in src folder actually exists in the destination folder it just checks if there are any files in src folder.


Solution

  • You can always use fs.existsSync(): http://nodejs.org/api/fs.html#fs_fs_exists_path_callback. Be sure to use the sync one, Grunt doesn't like async functions.

    Also; make sure you return a boolean.

    At the top of your Gruntfile.js:

    var fs = require('fs');
    

    In your task settings;

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