Terence Hirsch
Terence Hirsch

Reputation: 25

Trying to get folder path of file in Google Apps Script

I am trying to create a function in Google Apps Script that finds the file path of the folder. Here is the error: TypeError: Cannot read property 'appendParagraph' of null (line 20, file "Code")

function getRoot() {

  var doc = DocumentApp.getActiveDocument();
  var header = DocumentApp.getActiveDocument().getHeader();
  var name = doc.getName();
  var id = doc.getId();
  var txt = "Master Folder";
  var parents = [];
  var folders = DriveApp.getFileById(id).getParents();
  while (folders.hasNext()){
    var parent = folders.next();
    var n = parent.getName();
    parents.push(n);
  }
  var pLen = parents.length;
  for (i = 0; i < pLen; i++){
    txt = txt + "//" + parents[i];
  }

  var headerPar = header.appendParagraph(txt);


}

Upvotes: 2

Views: 7355

Answers (1)

Tanaike
Tanaike

Reputation: 201378

I believe your goal as follows.

  • You want to know the reason of the error message of TypeError: Cannot read property 'appendParagraph' of null.
  • You want to remove the error.
  • You want to retrieve the folder path of the active Google Document.

For this, how about this answer?

Modification points:

  • In your script, I think that the reason of your error message is the header is not existing in the Google Document. By this, header retrieved by getHeader() is null, and then, the error occurs. So in this case, please add the header using addHeader().
  • doc of var doc = DocumentApp.getActiveDocument(); can be used for getHeader().
  • If you want to retrieve the folder path from the root folder, I think that your script is required to be modified. In your current script, when the Google Document is put in the nested folders, only parent of the Document is retrieved.

When your script is modified using above points, it becomes as follows.

Modified script:

function getRoot() {
  var doc = DocumentApp.getActiveDocument();

  var header = doc.getHeader() || doc.addHeader();  // Modified

  var name = doc.getName();
  var id = doc.getId();
  var txt = "Master Folder";
  var parents = [];
  var folders = DriveApp.getFileById(id).getParents();

  // --- I modified below script
  while (folders.hasNext()) {
    var folder = folders.next();
    parents.push(folder.getName());
    folders = folder.getParents();
  }
  parents = parents.reverse();
  // ---

  var pLen = parents.length;
  for (i = 0; i < pLen; i++){
    txt = txt + "//" + parents[i];
  }
  var headerPar = header.appendParagraph(txt);
}
  • By this modification, when the header is existing, doc.getHeader() is used. When the header is not existing, doc.addHeader() is used. And, when the active Document is put to the folder path like root -> folder1 -> folder2, Master Folder//MyDrive//folder1//folder2 is put to the header.

References:

Upvotes: 3

Related Questions