Page 1 of 1

Path generation helper function

Posted: Fri Nov 04, 2016 4:13 pm
by gabrielp
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");