Click here to Skip to main content
15,890,690 members
Articles / Programming Languages / Javascript

Find Files with JavaScript

Rate me:
Please Sign up or sign in to vote.
4.85/5 (38 votes)
25 Mar 20021 min read 495.5K   13.3K   56   72
Find files or directory in client or server site with JavaScript

Image 1

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 to know whether the directory exists, use FolderExists().

JavaScript
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. Enumerators have some methods I have called like atEnd() and moveNext() in my sample.

JavaScript
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 is 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
JavaScript
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.


Written By
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralFixed all bugs (toggle and path reset) known issue with script timeout Pin
Uno19822-Sep-09 10:47
Uno19822-Sep-09 10:47 
GeneralRe: Fixed all bugs (toggle and path reset) known issue with script timeout Pin
lunar-fifth14-Sep-09 21:32
lunar-fifth14-Sep-09 21:32 
GeneralRe: Fixed all bugs (toggle and path reset) known issue with script timeout Pin
Uno198215-Sep-09 7:49
Uno198215-Sep-09 7:49 
GeneralThere are 2 bugs left in my source code. Pin
Uno198214-Jul-09 5:43
Uno198214-Jul-09 5:43 
QuestionHI, can i link results to the files!? Pin
ALEX CHIHAI16-Jun-09 10:16
ALEX CHIHAI16-Jun-09 10:16 
AnswerRe: HI, can i link results to the files!? Pin
Uno198214-Jul-09 5:35
Uno198214-Jul-09 5:35 
GeneralRe: HI, can i link results to the files!? Pin
RishiRaut23-Jan-11 7:06
RishiRaut23-Jan-11 7:06 
GeneralAdvanced Search including files from subdirectories, progressbar and delete function Pin
Uno19827-Jan-09 6:38
Uno19827-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 Pin
Uno198222-Apr-09 4:33
Uno198222-Apr-09 4:33 
QuestionCan the results be pushed to an Excel spreadhseet? Pin
popsui14-Oct-08 10:42
popsui14-Oct-08 10:42 
AnswerRe: Can the results be pushed to an Excel spreadhseet? [modified] Pin
Uno198231-Dec-08 9:22
Uno198231-Dec-08 9:22 
AnswerRe: Can the results be pushed to an Excel spreadhseet? Pin
Uno198216-Sep-09 10:11
Uno198216-Sep-09 10:11 
GeneralI can see nothing happenned=( Pin
nguk30-May-08 16:35
nguk30-May-08 16:35 
Generalno file found or search in progress [modified] Pin
crichardson1828-Apr-08 7:23
crichardson1828-Apr-08 7:23 
GeneralRe: no file found or search in progress Pin
Uno198213-Aug-09 9:42
Uno198213-Aug-09 9:42 
GeneralRe: no file found or search in progress Pin
crichardson1824-Aug-09 5:57
crichardson1824-Aug-09 5:57 
GeneralRe: no file found or search in progress Pin
Uno198224-Aug-09 8:41
Uno198224-Aug-09 8:41 
GeneralUpdate to sort by date (Delete function added) Pin
Uno19823-Apr-08 6:17
Uno19823-Apr-08 6:17 
GeneralRe: Update to sort by date (Delete function added) [I know this code is buggy] Pin
Uno198231-Dec-08 9:56
Uno198231-Dec-08 9:56 
GeneralVery Cool Pin
jftejadal28-Mar-08 11:36
jftejadal28-Mar-08 11:36 
GeneralUPDATE!! Sorting by Date() function Pin
Uno198227-Mar-08 11:23
Uno198227-Mar-08 11:23 
Questiondo not work in my computer Pin
emari216-Nov-07 4:19
emari216-Nov-07 4:19 
Questionhow to get the textfile from the system without giving the foldername in javascript in dynamically Pin
harikagupta2-Oct-07 20:39
harikagupta2-Oct-07 20:39 
QuestionEnumeration error Pin
SourceKode10-Aug-07 8:30
SourceKode10-Aug-07 8:30 
GeneralGood Very Good Pin
naimisar25-Jul-07 19:00
naimisar25-Jul-07 19:00 

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

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