How can I remove the parent folders in an array of paths? - javascript

I am using the following code in order to retrieve sub folder names from the path declared. This works fine but how do I then remove the path name so that the array is a list of just folder names?
var myPath = Folder ("Z:/My File System/Me/Work Files/Design");
var folders = getFolders (myPath);
function getFolders(sourceFolder) {
var folderArray = new Array();
var sFolders = sourceFolder.getFiles ();
var len = sFolders.length;
for (var i = 0; i < len; i++) {
var sFolder = sFolders[i];
if (sFolder instanceof Folder) {
folderArray.push(sFolder);
}
}
return folderArray;
}
Instead of returning:
Z:/My File System/Me/Work Files/Design/One
Z:/My File System/Me/Work Files/Design/Two
Z:/My File System/Me/Work Files/Design/Three
Z:/My File System/Me/Work Files/Design/Four
I need:
One
Two
Three
Four

You could implement something like this (assuming you can modify the Folder prototype, and it stores the path as this.path):
Folder.prototype.basename = function () {
return this.path.split('/').pop();
};
You would then append the base names to the array:
folderArray.push(sFolder.basename());

You could use split() like this, assuming there are no other slashes towards the end.
var sample = 'Z:/My File System/Me/Work Files/Design/Four'.split('/')
var result = sample[sample.length - 1]

Regexp the string. Start at the end, and work backward until the first '/'

Related

how to get subfolder names in javascript

i am using javascript in macros now i need to get all the names of subfolder from a local path, store these into an array and pass it to macros one bay one from javascript.using firefox where ActiveX is not available , so what the easiest way to get the subfolders names and pass it to macros?
Perhaps, this way is the easiest one:
/* indicate your folder */
var folder = "D:\\Temp";
var dir = imns.Cc["#mozilla.org/file/local;1"].createInstance(imns.Ci.nsILocalFile);
dir.initWithPath(folder);
var subFolders = [];
var subFolderEnum = dir.directoryEntries;
while (subFolderEnum.hasMoreElements()) {
var curSub = subFolderEnum.getNext().QueryInterface(imns.Ci.nsILocalFile);
if (curSub.isDirectory()) {
// subFolders.push(curSub.path); // for the full path
var subFolder = curSub.path;
subFolder = subFolder.substr(subFolder.lastIndexOf("\\") + 1);
subFolders.push(subFolder);
}
}
/* view the result */
alert(subFolders.join("\n"));

How to give a custom name to the objects in an array?

I have an upload form and for adding and deleting the files in a filelist I created an array that contains the files to send them in one request.
Creating the array
var filelist = [];
for(var i = 0; i < data.files.length; i++){
filelist.push(data.files[i]);
console.log(filelist);
}
Result in console
[File, File, File]
The files are contained in the array but now I want to give the names in the array the names of the files for deleting purposes.
So instead of [File, File, File], I would like to have for example [image01.jpg, image02.jpg, image03.jpg]
I have already tried
filelist.push(data.files[i].name);
result
["image01.jpg", "image02.jpg", "image03.jpg"]
But the files aren't added to the array? Can anybody help me with this please?
The reason I'm doing this is because I would like to try to remove files from the array on value and not on index.
code for deleting the files from the array
var idx = filelist.indexOf(file.name);
filelist.splice(idx,1);
You can set the name of the file as a key:
var filelist = {};
for(var i = 0; i < data.files.length; i++) {
var file = data.files[i];
filelist[file.name] = file;
}
And then use the delete operator to delete the file based on its name:
var filename = fileToDelete.name;
delete filelist[filename];

Javascript ignoring all files as opposed to one

I'm trying to get my javascript to ignore one file type extension that's held in a folder with a bunch of photoshop images. For all of the other file types in the folder I have it so that these file types populate a window and the user can import into their work space.
I have modified my script to ignore the file extension I want ignored, however it no longer populates the window with all of the other file types containted in the folder. But when I take out the file I want ignore from the folder, the window gets populated as it should.
This is what I have at the moment that checks my folder for the file types:
//Prompt for folder location
var Path = Folder.selectDialog("Select Folder Location for Renders")
// Use the path to the application and append the samples folder
var samplesFolder = Folder(Path)
//Get the files
var fileList = samplesFolder.getFiles()
//Creat Array to hold names
var renderTypes = new Array();
//Parse Initial name to get similar render elements
var beautyRender = fileList[0].name
beautyRender = beautyRender.substr(0, beautyRender.length-4)
//Get the render elements with a similar name
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Can anyone see what I've done wrong and need to modify?
Update
I'm still trying to get this to work and following the help from one of the posters below I have modified my code to the following:
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
renderTypes.push(fileList[i].name);
}
}
However, with this new code comes a new problem in that it returns every file contained in the folders and displays it.
I'm still stumped as to how I can get this to work as I would like. Please can anyone help me?
You're creating a sparse array, because you skip elements in renderTypes when you ignore a filename in fileList. That may be confusing your rendering code. Change to:
renderTypes.push(fileList[i].name);
What if :
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Wrong usage of the array
Missing ";"
Unnecessary use of "continue".
Managed to get a fix for this.
What I've ended up doing is creating a new function and passing that into my call for checking the folder locations.
function ignoreMe(f)
{
return f.name.match(/\.(stitchinfo)$/i) == null;
}
And the folder check:
var fileList = samplesFolder.getFiles(ignoreMe);

Can't get Content of the folder using Skydrive API

I have real problem in displaying the content of the folders which are located inside the root directory. It managed to determine the folders which are in the Files directory but when I try to do the same to one of those folders It doesn't work.
I delieve the problem in the path name of a WL.api. However I may be mistaken.
I used code samples from skydrive page of live connect development center. in the sample below I tried to determine folders first, but eventually I would like to get the names of all files stored in a particular directory.
WL.api({ path: "me/skydrive/files/myfolder", method: "get" }).then(
function (response) {
var items = response.data;
var outPuts = "";
var number = items.length
var tempos = new Array();
var foundFolder = 0;
for (var i = 0; i < items.length; i++) {
if (items[i].type === "folder" || items[i].type === "album") {
tempos[i] = items[i].name;
foundFolder += 1;
}
}
if (foundFolder == 0) {
folderss.innerHTML = ("Unable to find any folders");
}
else {
for (var i = 0; i < number; i++) {
outPuts = outPuts + tempos[i] + "<br /> <br />"
}
folderss.innerHTML = outPuts;
}
}
);
if I retain only "me/skydrive/files" for WL path. it works. But if I add any particular folder name afer it like in my case "me/skydrive/files/myfolder" the call returns nothing. or may be I shall declare a path like: "me/skydrive/files/folder.567391047.34282821!"
Thank you for anyone who can help.
I believe your problem is due to the fact that you are using an invalid path format. According to the examples from the docs, a valid path to list files has the following form: /OBJECT_ID/files, where OBJECT_ID may be replaced by me/skydrive to reference the Skydrive root folder.
The important things to note are that:
there can be a reference (OBJECT_ID) to only one object;
this reference can only be the ID of an object (as returned by the API) or a special alias such as me/skydrive;
/files should always be the last part of the path (assuming we do not need to use a query string).
Thus, to list the contents of your subfolder folder.567391047.34282821!, you should try using the following path format instead:
/folder.567391047.34282821!/files or even folder.567391047.34282821!/files (without the leading slash, as it seems to be optional).
Please let me know if this solves your issue.

Converting an absolute path to a relative path

Working in Node I need to convert my request path into a relative path so I can drop it into some templates that have a different folder structure.
For example, if I start with the path "/foo/bar" and want the relative path to "/foo", it would be "..", and for "/foo/bar/baz" it would be "../..".
I wrote a pair of functions to do this:
function splitPath(path) {
return path.split('/').map(dots).slice(2).join('/');
}
function dots() {
return '..';
}
Not sure if this is the best approach or if it's possible to do it with a regular expression in String.replace somehow?
edit
I should point out this is so I can render everything as static HTML, zip up the whole project, and send it to someone who doesn't have access to a web server. See my first comment.
If I understand you question correct you can use path.relative(from, to)
Documentation
Example:
var path = require('path');
console.log(path.relative('/foo/bar/baz', '/foo'));
Node.js have native method for this purposes: path.relative(from, to).
This might need some tuning but it should work:
function getPathRelation(position, basePath, input) {
var basePathR = basePath.split("/");
var inputR = input.split("/");
var output = "";
for(c=0; c < inputR.length; c++) {
if(c < position) continue;
if(basePathR.length <= c) output = "../" + output;
if(inputR[c] == basePathR[c]) output += inputR[c] + "/";
}
return output;
}
var basePath ="/foo"
var position = 2;
var input = "/foo";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar/baz";
console.log(getPathRelation(position,basePath,input));
Result:
(an empty string)
../
../../

Categories