cancel
Showing results for 
Search instead for 
Did you mean: 

check if folder exists- Alfresco Javascript

sakshik
Star Contributor
Star Contributor

How do I create a folder only if it doesn't already exists.

or

How do I check if a folder exists inside a folder(Node)

in alfresco Javascript

1 ACCEPTED ANSWER

mehe
Elite Collaborator
Elite Collaborator

Let's assume your "parent" folder node is parentFolderNode and you want to create a new folder with the name "newFolder" in it:   

var newFolderName="newFolder";
var newFolderNode=parentFolderNode.childByNamePath(newFolderName);
if (newFolderNode === null) {
  //which means newFolder does not exists, so create it
  newFolderNode=parentFolderNode.createFolder(newFolderName);
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

If you don't have parentFolderNode already, you can get it via companyhome.childByNamePath(pathToParent);

Where pathToParent is a string like "mydir/nextdir/theFolder". So you could also use companyhome as your "parent" with a longer path.

 If you want to create all path-elements on the "way" use a function with loop:

function createPathAsNeeded(path) {
     var apath=path.split("/");
     var node=companyhome;
     for each (var adir in apath) {
          if (node.childByNamePath(adir) == null) {
               node=node.createFolder(adir);
          } else {
               node=node.childByNamePath(adir);
          }
     }
     return node;
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

(could also be done recursive - don't know which version is better for understanding...)

View answer in original post

2 REPLIES 2

mehe
Elite Collaborator
Elite Collaborator

Let's assume your "parent" folder node is parentFolderNode and you want to create a new folder with the name "newFolder" in it:   

var newFolderName="newFolder";
var newFolderNode=parentFolderNode.childByNamePath(newFolderName);
if (newFolderNode === null) {
  //which means newFolder does not exists, so create it
  newFolderNode=parentFolderNode.createFolder(newFolderName);
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

If you don't have parentFolderNode already, you can get it via companyhome.childByNamePath(pathToParent);

Where pathToParent is a string like "mydir/nextdir/theFolder". So you could also use companyhome as your "parent" with a longer path.

 If you want to create all path-elements on the "way" use a function with loop:

function createPathAsNeeded(path) {
     var apath=path.split("/");
     var node=companyhome;
     for each (var adir in apath) {
          if (node.childByNamePath(adir) == null) {
               node=node.createFolder(adir);
          } else {
               node=node.childByNamePath(adir);
          }
     }
     return node;
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

(could also be done recursive - don't know which version is better for understanding...)

sakshik
Star Contributor
Star Contributor

thanks a lot @martin