Comparing File Contents of Files on Google Drive using Google Apps Script

Gists

This is a sample script for comparing the file contents of files on Google Drive using Google Apps Script.

Sample script

Before you use this script, please enable Drive API at Advanced Google services. And also, please set the file IDs you want to check whether the file contents of the files are the same.

function checkFiles_(f, checks = ["md5Checksum", "sha1Checksum", "sha256Checksum"]) {
  files = f.map(id => DriveApp.getFileById(id));
  const fields = [...checks, "id"].join(",");
  const o = files.reduce((o, f) => {
    const mimeType = f.getMimeType();
    if (["FOLDR", "SHORTCUT"].some(m => mimeType == MimeType[m])) {
      throw new Error("Folders cannot be checked.");
    }
    let obj;
    if (mimeType.includes("application/vnd.google-apps")) {
      const name = f.getName();
      f.setName("temp");
      Utilities.sleep(2000);
      obj = Drive.Files.insert({ title: "temp", mimeType: MimeType.PDF }, f.getBlob(), { supportsAllDrives: true, fields });
      f.setName(name);
      Drive.Files.remove(obj.id); // If an error occurs, please use DriveApp.getFileById(obj.id).setTrashed(true);
    } else {
      obj = Drive.Files.get(f.getId(), { supportsAllDrives: true, fields });
    }
    checks.forEach(e => o[e] = o[e] ? [...o[e], obj[e]] : [obj[e]]);
    return o;
  }, {});
  return Object.values(o).every(e => [...new Set(e)].length == 1);
}

// Please run this function.
function main() {
  const file1 = "###fileId1###"; // Please set your file ID of file 1.
  const file2 = "###fileId2###"; // Please set your file ID of file 2.

  const check = checkFiles_([file1, file2]);
  const res = `"${file1}" and "${file2}" are${
    check ? " " : " not "
  }the same data.`;
  console.log(res);
}

Note

Reference

 Share!