Click here to Skip to main content
Click here to Skip to main content

Find files with JavaScript

, 25 Mar 2002
Rate this:
Please Sign up or sign in to vote.
Find files or directory in client or server site with JavaScript

Introduction

Maybe you want to have list of  server or client files in your web page to uploading or downloading or changing . JScript allow you to do this. You can capture all files type , size , properties in all directories and use them easily. In this sample I use this technique for searching files in local hard drive.

Necessary Attention: your browser should have access to run ActiveX objects. If receive a error message telling "Automatic Server Can't Create Object" you most go to Internet Option and in security tab select custom level in Local part and change options to get effect.

ActiveX Objects

For working with Files and directory you should make a server object as Scripting.FileSystemObject then with GetDirectory() method can get a directory object. If you want know the directory is use FolderExists().

var Fo = new ActiveXObject("Scripting.FileSystemObject");

Enumerator

Enumerators are an array of Directory or File objects such that you can use methods to get special file or sub directory that are in defined path. Enumerator have some methods I have called like atEnd() and moveNext() in my sample.

function FindFile(FOo)
{
    //Get array of files including in FOo directory object
    var FSo = new Enumerator(FOo.Files);
    
    // Getting all files in FSo object
    for (i=0;!FSo.atEnd();FSo.moveNext())

    ...
}

Files Object Properties

For getting a object that is in Enumerator object you must use item() and it returns a file or directory object that are in current place of Enumerator. Then you can use Files properties that are listed.

  • Attributes
  • DateCreated
  • DateLastAccessed
  • DateLastModified
  • Drive
  • Name
  • ParentFolder
  • Path
  • ShortName
  • ShortPath
  • Size
  • Type
FSo.item().name // File name
FSo.item().type // Description defining the file extension
FSo.item().size // File size in byte

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

AFShin Dehghani
Web Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions

 
Questionrecurse PinmemberTlhogi2420-May-14 22:24 
QuestionERROR .........resultset not positioned properly PinmemberMember 965495830-Mar-14 19:41 
Bugerror PinmemberMember 965495816-Feb-14 23:52 
GeneralRe: error PinmemberPatrik Misencik19-Feb-14 2:24 
GeneralRe: error PinmemberMember 965495819-Feb-14 18:15 
Questionthanks mate Pinmemberivan coene17-Jun-13 3:54 
GeneralMy vote of 5 PinmemberMember 913753919-Jun-12 4:42 
QuestionHow to add view option PinmemberRishiRaut23-Jan-11 7:10 
QuestionHow to upload these files Pinmemberdsfdfdfdf343434322-Sep-10 3:31 
QuestionCan this script be used to search .avi files? PinmemberDave Herrell25-Dec-09 7:09 
GeneralMy vote of 1 Pinmemberdvg.madhu7-Oct-09 20:19 
GeneralUpdate!! - Export to excel spreadsheet added!! PinmemberUno198216-Sep-09 10:14 
GeneralFIXED!!! New Windows Update Breaks ActiveX security fuctions PinmemberUno198215-Sep-09 10:04 
GeneralFixed all bugs (toggle and path reset) known issue with script timeout PinmemberUno19822-Sep-09 10:47 
GeneralRe: Fixed all bugs (toggle and path reset) known issue with script timeout Pinmemberlunar-fifth14-Sep-09 21:32 
GeneralRe: Fixed all bugs (toggle and path reset) known issue with script timeout PinmemberUno198215-Sep-09 7:49 
GeneralThere are 2 bugs left in my source code. PinmemberUno198214-Jul-09 5:43 
QuestionHI, can i link results to the files!? PinmemberALEX CHIHAI16-Jun-09 10:16 
AnswerRe: HI, can i link results to the files!? PinmemberUno198214-Jul-09 5:35 
GeneralRe: HI, can i link results to the files!? PinmemberRishiRaut23-Jan-11 7:06 
GeneralAdvanced Search including files from subdirectories, progressbar and delete function PinmemberUno19827-Jan-09 6:38 
Below is the advanced search code in its entirety... you will also need the Progressbar.gif to be in the same directory as the advancedsearch.htm
 
<HTML><HEAD><TITLE>        
Drive Search</TITLE></HEAD>
 

 
<STYLE>
img {
padding: 0px; 
margin: 0px; 
border: none;
}
 
.formItem {
     color: #000000;
     border: 1px solid #aaaaaa;
     background-color: #eeeeee;
}
 
.find {
      color: #0000ff;
      font: 10px Arial;
      }
 
.title {
      background-color: #dddddd;
      color: #000000;
      font: 12px arial;
      font-weight: bold;
      text-align: center;
      }
 
A {
     color: blue;
     text-decoration: none;
}
 
A:hover {
     text-decoration: underline;
}
 
</STYLE>
 
<SCRIPT>
 

// Establish a few environment variables.
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
var result = new String( );
var FileName = new String( );
var Extention = new String( );
var filepath = new Array();
var subfoldarray = new Array();
var x = 0;
var c = 0;
 
// Converts file & folder byte size values to computer metric (bytes, KB, MB, GB or TB).   returns a string.
function toMetric( bytes ) {
 
     // Check for Terabytes (TB).
     if( bytes >= 1099511627776 ) { return ( Math.floor( bytes / 1099511627776 ) + ' TB' ); }

     // Check for Gigabytes (GB).
     if( bytes >= 1073741824 ) { return ( Math.floor( bytes / 1073741824 ) + ' GB' ); }

     // Check for Megabytes (MB).
     if( bytes >= 1048576 ) { return ( Math.floor( bytes / 1048576 ) + ' MB' ); }

     // Check for Kilobytes (KB).
     if( bytes >= 1024 ) { return ( Math.floor( bytes / 1024 ) + ' KB' ); }

     // The file is less than one KB, just return size as 1 KB like Windows does.
     return '1 KB';
}
 

// Show the contents of a clicked sub-folder.
function subFolder( path ) {
     // Update the txtPath field with the new search folder.
     frmSearch.txtPath.value = unescape(path);
	 // Restart a new search with the new folder.
     scan( );
}
 

// Scans the given path for files matching the given mask.
function FindFile( searchPath ) {
 
     	// Extablish a table color toggle.
     	var toggle = true;
 
        // Establish enumerator to step from folder to folder in the SubFolders collection.
        var folderEnum = new Enumerator( searchPath.SubFolders );
 
        k=0;
		for( var i = 0; !folderEnum.atEnd( ); folderEnum.moveNext()) {
				
             // Use a variable to hold the current file object to shorten the code below.
             var folder = folderEnum.item( );
			 // send folder path into array for use later
			 subfoldarray[k]=folder.path;
			 //call subfolder function to search through for files
			 subFolder(subfoldarray[k]);
			 k++;
  		}
 
     // Establish enumerator to step from item to item in the folder contents.
     var fileEnum = new Enumerator( searchPath.Files );
 
     // Iterate through the files in the collection.   Scan for files fitting the file mask.
     x=0;
	 for( var i = 0; !fileEnum.atEnd( ); fileEnum.moveNext( ) ) {
	
          // Use a variable to hold the current file object to shorten the code below.
          var file = fileEnum.item( );
 
          // Validate current file against search filename parameter.
          if( FileName == "*" || file.name.slice( 0, file.name.lastIndexOf( "." ) ).toLowerCase( ).indexOf( FileName ) > -1 ) {
 
               // Validate current file extention against search file extention parameter.
               if( Extention == "*" || file.name.slice( file.name.lastIndexOf( "." ) + 1 ).toLowerCase( ).indexOf( Extention ) > -1 ) {
 
                    // Add the file to the table result string.
                   var mydate = new Date()
				   //set mydate for use in output and sort
				   mydate.setYear(mydate.getYear()- frmSearch.form_date.value)
				
					if (file.DateLastModified <= mydate){
							
							filepath[x] = new filefunction(file.Path, file.name, file.type, file.DateLastModified, file.size);
							//alert(filepath[x].Path);
							x++;	 
							
					}
               }
          }
     }
	 
	    // calls the sort function on the array
	   	filepath.sort(sortDateModified);
		
		for(i=0; i<x; i++){	
			//outputs sorted results
			c++
			//outputs files to table
			result += 
                         '<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +
                         '<TD NOWRAP><FONT CLASS="find">&nbsp;<A TARGET="_blank" HREF="' +
                         filepath[i].Path + '">' + filepath[i].name +
                         '</A>&nbsp;</FONT></TD>'+
						 '<TD NOWRAP><FONT CLASS="find"> '+ searchPath +' </FONT></TD>'
						 +
                         '<TD NOWRAP><FONT CLASS="find"> ' + filepath[i].type + ' </FONT></TD>' +
						 '<TD NOWRAP><FONT CLASS="find"> '+ filepath[i].DateLastModified +' </FONT></TD>' +
                         '<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;' +
						
						 toMetric( filepath[i].size )   + '&nbsp;</FONT></TD><TD><input style="visibility:visible;" id ="delete" type="Button" name="del" class="formItem" value="Delete" onClick="deleteFile(this, &quot;'+ escape(searchPath) + '/'+ filepath[i].name + '&quot; , &quot;'+ filepath[i].name + '&quot;);"></TD></TR>'; 
						// Toggle the color toggle variable.
                    	toggle = !toggle;
		// sends the cout out to Search Results:
		frmSearch.resultcnt.value = c + " Files"; 
		}
		
}
// filefunction holds values of multidem array for sorting and other functions
function filefunction(path, Name, Type, datemodified, Size){
			this.Path = path;
			this.name = Name;
			this.type = Type;
			this.DateLastModified = datemodified;
			this.size = Size;
}
 
// delete file function
function deleteFile (fldname, fpath, fname){
//alert (escape(fpath));
var answer = confirm('Are you sure you want to delete '+fname+'?');
	if(answer){
	var deleteobject;
	deleteobject = new ActiveXObject("Scripting.FileSystemObject");
	deleteobject.DeleteFile(unescape(fpath));
	//calls header output function to and rescans after the file is deleted
	disabledelete(fldname)
	}else{}
}
 
function disabledelete(flaname){
flaname.style.visibility = 'hidden';
}
 
// sort date function
function sortDateModified(a, b) {
    var x = b.DateLastModified;
    var y = a.DateLastModified;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
 
function progressbar(){
	var width = 320;
	var height = 200;
	var left = (screen.width - width)/2;
	var top = (screen.height -  height)/2;
	newwindow2=window.open('','Progress','height=200,width=320,top='+top+',left='+left+'');
	var tmp = newwindow2.document;
	tmp.write('<html><head><title>Progress</title>');
	tmp.write('</head><body><p>Please Wait<br><br><img src="progressbar.gif"/></p>');
	tmp.write('</body></html>');
	tmp.close();	
}
 
// sends header output to page and scans directory
function headerOutput(){
		 //resets path to main directory
		 frmSearch.txtPath.value = frmSearch.txtPath.value; 
		  //sets the header info
		  frmSearch.resultcnt.value = 0 + " Files";
		  result =
               '<TABLE BORDER="0" WIDTH="100%" CELLPADDING="5"><TR>' +
               '<TD WIDTH="60%" CLASS="title">File Name</TD>' +
               '<TD WIDTH="20%" CLASS="title">Path</TD>'+
			   '<TD WIDTH="25%" CLASS="title">Type</TD>' +
			   '<TD WIDTH="15%" CLASS="title">Last Modified</TD>' +
               '<TD WIDTH="15%" CLASS="title">Size</TD>' +
			   '<TD WIDTH="15%" CLASS="title">Delete File</TD></TR>';
//resets total count for new search
c=0;
//reset arrays for new search
FileName = new String( );
Extention = new String( );
filepath = new Array();
subfoldarray = new Array();
//scans the current directory
progressbar();
scan();
newwindow2.close();
 
}
 

// Validates path and filename and initiates the file scan.
function scan( ) {
     // Parse filename and extention from the given mask.
     FileName = ( frmSearch.txtMask.value.lastIndexOf( "." ) > -1 ) ? frmSearch.txtMask.value.slice( 0, frmSearch.txtMask.value.lastIndexOf( "." ) ) : ( frmSearch.txtMask.value.length > 0 ) ? frmSearch.txtMask.value.toLowerCase( ) : "*";
     Extention = ( frmSearch.txtMask.value.lastIndexOf( "." ) > -1 ) ? frmSearch.txtMask.value.slice( frmSearch.txtMask.value.lastIndexOf( "." ) + 1 ).toLowerCase( ) : "*";
 
     // Validate the given path.
     if( frmSearch.txtPath.value.length > 0 && fso.FolderExists( frmSearch.txtPath.value ) ) {
 

          // Collect valid filenames.
          FindFile( fso.GetFolder( frmSearch.txtPath.value ) );
 
          // Close and display search results table.
		  outPut.innerHTML = result + "</TABLE>";
 
     } else {
 
          // Path is invalid.   Alert user.
          alert( "Please enter a valid Path before proceeding." );
     }
}
 

</SCRIPT>
 

 
<BODY onLoad="frmSearch.txtMask.focus( ); frmSearch.txtMask.select( )" BGCOLOR="#ffffff" TOPMARGIN="0" LEFTMARGIN="0">
<center>
<FORM ID="frmSearch" NAME="frmSearch">
 
<TABLE BORDER="0" CELLPADDING="0" STYLE="border-collapse: collapse;" CELLPADDING="2">
<TR>
     <TD><FONT FACE="Arial" SIZE="2"><B> Mask :&nbsp; </B></FONT></TD>
     <TD><INPUT TYPE="text" VALUE="*.*" ID="txtMask" NAME="txtMask" CLASS="formItem" STYLE="width:600;"></TD>
</TR>
<TR>
     <TD><FONT FACE="Arial" SIZE="2"><B> Path: &nbsp; </B></FONT></TD>
     <TD><INPUT TYPE="text" VALUE="Y:\" ID="txtPath" NAME="txtPath" CLASS="formItem" STYLE="width:600; visibility:visible;"><INPUT TYPE="text" VALUE="Y:\" ID="txtOrigPath" NAME="txtOrigPath" CLASS="formItem" STYLE="width:0; visibility:hidden;"></TD>
	 
</TR>
<TR>
<TD>&nbsp;</TD>
<TD><font size="-1" color="#666666"><i> *Following the search the path will reflect the last folder found in the specified directory. <u><br>example</u>: search "c:\windows" results "c:\windows\system\"</i></font></TD>
</TR>
<TR>
<TD>&nbsp;</TD>
</TR>
<TR>
     <TD>&nbsp;</TD>
     	  <TD>
          <INPUT TYPE="button" VALUE="Search" CLASS="formItem" STYLE="width:150;"
		 onClick="headerOutput( ); frmSearch.txtMask.focus( ); frmSearch.txtMask.select( );return false;">
          &nbsp; &nbsp; &nbsp;
          &nbsp;&nbsp;&nbsp;&nbsp;Older Than:<select name="form_date">
		  <option value="20">20yrs</option><option value="19">19yrs</option><option value="18">18yrs</option>
		  <option value="17">17yrs</option><option value="16">16yrs</option><option value="15">15yrs</option><option value="14">14yrs</option>
		  <option value="13">13yrs</option><option value="12">12yrs</option><option value="11">11yrs</option><option value="10">10yrs</option>
			   <option value="9">9yrs</option><option value="8">8yrs</option><option value="7">7yrs</option><option value="6">6yrs</option><option value="5">5yrs</option><option value="4">4yrs</option><option value="3">3yrs</option></select>
			    <font size="-1" color="#666666"><i> < Please select the age of the files</i></font></TD>
          </TD>
</TR>
<TR>
     <TD COLSPAN="2">
          <BR> <FONT FACE="arial" SIZE="2"><B> Search Result: </B></FONT><input readonly style="text-align:center; border:none; color:red;" name="resultcnt" size="6" value="">
          &nbsp;&nbsp;<font size="-1" color="#666666"><i>  <u><b>Tip</b></u>: &nbsp;To cycle through files and delete quicker use Tab2x, Enter2x combination</i></font>
		  <HR>
		  <div id="preload" style="visibility:hidden;"><img height="20" width="500" src="progressbar.gif"/></div>
		  <DIV ID="outPut"></DIV>
     </TD>
</TR>
</TABLE>
 
</FORM>
 
</center>
</BODY></HTML>

GeneralRe: Advanced Search including files from subdirectories, progressbar and delete function PinmemberUno198222-Apr-09 4:33 
QuestionCan the results be pushed to an Excel spreadhseet? Pinmemberpopsui14-Oct-08 10:42 
AnswerRe: Can the results be pushed to an Excel spreadhseet? [modified] PinmemberUno198231-Dec-08 9:22 
AnswerRe: Can the results be pushed to an Excel spreadhseet? PinmemberUno198216-Sep-09 10:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 26 Mar 2002
Article Copyright 2002 by AFShin Dehghani
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid