简体   繁体   中英

JavaScript - extract folder names

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.

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.

您不能在浏览器中通过Javascript来执行此操作,因为JS无法从浏览器访问文件系统。

假设脚本将在尝试访问本地硬盘驱动器的上下文中执行(例如,在cscript或经典ASP中),那么最好的选择是FileSystemObject

如果要在Web浏览器中执行JavaScript,则不能这样做,因为在这种情况下,出于安全原因,JavaScript无法访问本地文件系统。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM