views:

1157

answers:

5

Hello. I'm fairly new to JavaScript.

Given a local machine's folder path (Windows), I was wondering how you can extract the names of all the possible folders in the current path, without the knowledge of how many folders there are or what they are called.

Thank you very much in advance.

+1  A: 

You cannot do this via Javascript in a browser as the JS doesn't have that kind of access to the file system from a browser.

Mitchel Sellers
A: 

If you're executing JavaScript in a web browser then you can't, because in this scenario JavaScript has no access to the local file system for security reasons.

John Topley
+1  A: 

Assuming the script will execute in a context where it makes sense to try and access the local hard drives (e.g. in cscript or classic ASP), your best bet is the FileSystemObject.

Daniel Earwicker
+1  A: 

Yes, the environment I am worknig in can access my local machine. Thanks for feedback, I will look into FileSystemObject.

+5  A: 

Here is a little script to get you started with FileSystemObject in conjuction with JScript:

var fso   = new ActiveXObject("Scripting.FileSystemObject");
var shell = new ActiveXObject("WScript.Shell");
var path  = "%ProgramFiles%";

var programFiles = fso.GetFolder(shell.ExpandEnvironmentStrings(path));
var subFolders   = new Enumerator(programFiles.SubFolders);

while (!subFolders.atEnd())
{
  var subFolder = subFolders.item();
  WScript.Echo(subFolder.Name);
  subFolders.moveNext();
}

Call that with csript.exe on the command line:

cscript subfolders.js

The Windows Script 5.6 Documentation holds all the details you need on this topic (and many others). Download it and have it around, it is really helpful. On Windows systems, a little knowledge of FileSystemObject and it's relatives really can save the day.

Tomalak