Home > OS >  Google script Type error when try to move files to folder
Google script Type error when try to move files to folder

Time:12-22

I'm trying to select multiple files depending on the mime type (JPG and Google Docs in this example) and move to specific folders for each type. So I tried the following:

function test() {
  var srcfolderId = "abcdefghi"; 

  var jpgFolderID=DriveApp.getFolderById(srcfolderId).createFolder("jpgfiles").getId();
  var gdocFolderID=DriveApp.getFolderById(srcfolderId).createFolder("gdocfiles").getId();

  var jpgfiles=DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPEG);
  var gdocfiles=DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.GOOGLE_DOCS);

  jpgfiles.moveTo(jpgFolderID);
  gdocfiles.moveTo(gdocFolderID);
}

But this creates the error:

TypeError: jpgfiles.moveTo is not a function

What should I need to do to escape from this error? Should I use a different way to move multiple files to a specific folder?

CodePudding user response:

Modification points:

  • The reason for your issue of TypeError: jpgfiles.moveTo is not a function is due to that the argument of moveTo is the folder object. In your script, the folder ID is used.
  • DriveApp.getFolderById(srcfolderId) can be declared as one variable.
  • getFilesByType returns FileIterator.

When these points are reflected in your script, it becomes as follows.

Modified script:

function test() {
  var srcfolderId = "abcdefghi";
  var folder = DriveApp.getFolderById(srcfolderId);
  var jpgFolder = folder.createFolder("jpgfiles");
  var gdocFolder = folder.createFolder("gdocfiles");
 
  var jpgfiles = folder.getFilesByType(MimeType.JPEG);
  while (jpgfiles.hasNext()) {
    jpgfiles.next().moveTo(jpgFolder);
  }

  var gdocfiles = folder.getFilesByType(MimeType.GOOGLE_DOCS);
  while (gdocfiles.hasNext()) {
    gdocfiles.next().moveTo(gdocFolder);
  }
}

References:

CodePudding user response:

Try adding something like this:

while(jpgfiles.hasNext()) {
  let file = jpgfiles.next();
  file.mmoveTo()....
  • Related