Path generation helper function

Post Reply
User avatar
gabrielp
Advanced member
Posts: 645
Joined: Fri Aug 08, 2014 4:31 pm
Location: Boston
Contact:

Path generation helper function

Post by gabrielp » Fri Nov 04, 2016 4:13 pm

I developed this function for Portals recently and figured it might help people who have this problem in the future. If you need to create a directory structure to save a file to, you may find that your script works fine for writing that file on OSX but fails on Windows. For whatever reason, Switch will fail writing (using s.copy for example) if the parent folder does not exist on Windows.

This function will take path segments, ensure each exists, and return to you the absolute path.

Code: Select all

// Checks to make sure an array of path segments exists.
// If not, it recursively creates the folder heirarchy.
var initDirectory = function(s, verboseDebugging, pathArray, key) {
	cwd = "";

	forEach(pathArray, function(pathSegment, i){
		cwd += pathSegment;
		dir = new Dir(cwd);

		if(!dir.exists){

			dir.cdUp();

			if(verboseDebugging === true){
				s.log(-1, "initDirectory: '" + dir.absPath + "' '"+pathSegment+"' did not exist. Creating it.");
			}

			try {
				dir.mkdir(pathSegment);

			} catch (e) {
				s.log(3, "Could not make '" + key + "'. " + e);
			}

		}

		cwd += getDirectorySeperator(s);

	});

	lastDir = new Dir(cwd);
	return lastDir.absPath;
}
You provide the function an array of path segments. For example: ["/var/www/", "myApp", "myCustomer"] would verify or create and return the following path "/var/www/myApp/myCustomer".

Code: Select all

// From Portals...
var scriptDataFolder = s.getSpecialFolderPath('ScriptData');
var etherPath = initDirectory(s, verboseDebugging, [scriptDataFolder, etherName], "ether folder");
var channelFolder = initDirectory(s, verboseDebugging, [etherPath, channelKey], "channel folder");
var tempFolder = initDirectory(s, verboseDebugging, [channelFolder, "temp"], "temp channel folder");
var packLocation = initDirectory(s, verboseDebugging, [tempFolder, job.getUniqueNamePrefix()], "pack location");
var datasetDir = initDirectory(s, verboseDebugging, [packLocation, "datasets"], "dataset location");
Free Switch scripts: open-automation @ GitHub
Free Switch apps: open-automation @ Enfocus appstore

If I've helped you and you'd like to say thanks, consider adding me on LinkedIn and leaving me an endorsement or recommendation. It helps a lot!

Post Reply