Tagged with " javascript"

File System Iterator by JScript

Nov 19, 2010 by     No Comments    Posted under: New Technologies, Scripting, Tips & Techniques

One way to test your mastery of a programming language is to write a file system iterator. Basically the input is a path of a folder and then the program you write with a particular programming language iterates recursively into this folder. The SAS example can be found here and the VBScript example here

Here I show the iterator in JScript, id est, Microsoft JavaScript. Call the following code “traverse.js”:

function prt(Str){
// Print a string
WScript.Echo(Str);
}


function prtFile(f){
// Print the path of a file
prt(f.Path+", "+f.DateLastModified);
}


function prtFolder(d){
// Print the path of a folder
prt(d.Path+"\\");
}


function Iter(fldrPth,fso,ActionOnFile,ActionOnFolder){
if (fso.FolderExists(fldrPth)){
var fldr=fso.GetFolder(fldrPth);
var fl=new Enumerator(fldr.Files);
for (fl.moveFirst();!fl.atEnd();fl.moveNext()){
ActionOnFile(fl.item());
}
var d=new Enumerator(fldr.SubFolders);
for (d.moveFirst();!d.atEnd();d.moveNext()){
ActionOnFolder(d.item());
Iter(d.item().Path,fso,ActionOnFile,ActionOnFolder);
}
}
}


objFSO=new ActiveXObject("Scripting.FileSystemObject");
Iter(WScript.Arguments(0),objFSO,prtFile,prtFolder);

To test, run a CMD shell in windows and type something like

traverse "C:\Windows"

The program lists all the subfolders and files together with the file’s last modified time recursively.

Check out the BioNews, a very handy daily recap of the latest industry news!