Click here to Skip to main content
15,891,607 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.6K   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

 
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 
I know I answered my own request with this one but i needed it and I worked on it till I figured it out. So here ya go hope it benifits someone else who needed it.

<HTML><HEAD><TITLE>        <br />
</TITLE></HEAD><br />
<br />
<br />
<br />
<STYLE><br />
<br />
.formItem {<br />
     color: #000000;<br />
     border: 1px solid #aaaaaa;<br />
     background-color: #eeeeee;<br />
}<br />
<br />
.find {<br />
      color: #0000ff;<br />
      font: 10px Arial;<br />
      }<br />
<br />
.title {<br />
      background-color: #dddddd;<br />
      color: #000000;<br />
      font: 12px arial;<br />
      font-weight: bold;<br />
      text-align: center;<br />
      }<br />
<br />
A {<br />
     color: blue;<br />
     text-decoration: none;<br />
}<br />
<br />
A:hover {<br />
     text-decoration: underline;<br />
}<br />
<br />
</STYLE><br />
<br />
<br />
<br />
<SCRIPT LANGUAGE="JavaScript"><br />
<br />
<br />
// Establish a few environment variables.<br />
var fso = new ActiveXObject( "Scripting.FileSystemObject" );<br />
var result = new String( );<br />
var FileName = new String( );<br />
var Extention = new String( );<br />
var filepath = new Array();<br />
var x = 0;<br />
<br />
// Converts file & folder byte size values to computer metric (bytes, KB, MB, GB or TB).   returns a string.<br />
function toMetric( bytes ) {<br />
<br />
     // Check for Terabytes (TB).<br />
     if( bytes >= 1099511627776 ) { return ( Math.floor( bytes / 1099511627776 ) + ' TB' ); }<br />
<br />
     // Check for Gigabytes (GB).<br />
     if( bytes >= 1073741824 ) { return ( Math.floor( bytes / 1073741824 ) + ' GB' ); }<br />
<br />
     // Check for Megabytes (MB).<br />
     if( bytes >= 1048576 ) { return ( Math.floor( bytes / 1048576 ) + ' MB' ); }<br />
<br />
     // Check for Kilobytes (KB).<br />
     if( bytes >= 1024 ) { return ( Math.floor( bytes / 1024 ) + ' KB' ); }<br />
<br />
     // The file is less than one KB, just return size as 1 KB like Windows does.<br />
     return '1 KB';<br />
}<br />
<br />
<br />
// Show the contents of a clicked sub-folder.<br />
function subFolder( path ) {<br />
<br />
     // Update the txtPath field with the new search folder.<br />
     frmSearch.txtPath.value = unescape( path );<br />
<br />
     // Restart a new search with the new folder.<br />
     scan( );<br />
}<br />
<br />
<br />
// Scans the given path for files matching the given mask.<br />
function FindFile( searchPath ) {<br />
<br />
     // Extablish a table color toggle.<br />
     var toggle = true;<br />
<br />
     // If chkShowFolders is checked, display the sub-folders.<br />
     if( frmSearch.chkShowFolders.checked ) {<br />
<br />
          // Check to see if the current folder is the drive root.<br />
          if( fso.GetParentFolderName( frmSearch.txtPath.value ).length > 0 ) {<br />
<br />
               // Add the parent folder to the table result string.<br />
               result +=<br />
                    '<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +<br />
                    '<TD NOWRAP><FONT CLASS="find">&nbsp;<A HREF="#" onClick="subFolder( \'' +<br />
                    escape( fso.GetParentFolderName( frmSearch.txtPath.value ) ) +<br />
                    '\' ); return false;">..</A>&nbsp;</FONT></TD>' +<br />
                    '<TD NOWRAP><FONT CLASS="find"> Parent folder </FONT></TD>' +<br />
                    '<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;</FONT></TD></TR>';<br />
<br />
               // Toggle the color toggle variable.<br />
               toggle = !toggle;<br />
          }<br />
<br />
          // Establish enumerator to step from folder to folder in the SubFolders collection.<br />
          var folderEnum = new Enumerator( searchPath.SubFolders );<br />
<br />
          // Iterate through the folders in the collection.<br />
          for( var i = 0; !folderEnum.atEnd( ); folderEnum.moveNext( ) ) {<br />
				<br />
               // Use a variable to hold the current file object to shorten the code below.<br />
               var folder = folderEnum.item( );<br />
			   		   <br />
			   // Add the folder to the table result string.<br />
               result +=<br />
                    '<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +<br />
                    '<TD NOWRAP><FONT CLASS="find">&nbsp;<A HREF="#" ' +<br />
                    'onClick="subFolder( \'' + escape( folder.Path ) + '\' ); return false;">' + folder.name +<br />
                    '</A>&nbsp;</FONT></TD>' +<br />
                    '<TD NOWRAP><FONT CLASS="find"> ' + folder.type + ' </FONT></TD>' <br />
                    '<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;</FONT></TD></TR>';<br />
<br />
               // Toggle the color toggle variable.<br />
               toggle = !toggle;<br />
          }<br />
     }<br />
<br />
     // Establish enumerator to step from item to item in the folder contents.<br />
     var fileEnum = new Enumerator( searchPath.Files );<br />
<br />
     // Iterate through the files in the collection.   Scan for files fitting the file mask.<br />
     x=0;<br />
	 for( var i = 0; !fileEnum.atEnd( ); fileEnum.moveNext( ) ) {<br />
	<br />
          // Use a variable to hold the current file object to shorten the code below.<br />
          var file = fileEnum.item( );<br />
<br />
          // Validate current file against search filename parameter.<br />
          if( FileName == "*" || file.name.slice( 0, file.name.lastIndexOf( "." ) ).toLowerCase( ).indexOf( FileName ) > -1 ) {<br />
<br />
               // Validate current file extention against search file extention parameter.<br />
               if( Extention == "*" || file.name.slice( file.name.lastIndexOf( "." ) + 1 ).toLowerCase( ).indexOf( Extention ) > -1 ) {<br />
<br />
                    // Add the file to the table result string.<br />
                   var mydate = new Date()<br />
				 <br />
				   mydate.setYear(mydate.getYear()- frmSearch.form_date.value)<br />
				<br />
					if (file.DateLastModified <= mydate){<br />
							<br />
							filepath[x] = new filefunction(file.Path, file.name, file.type, file.DateLastModified, file.size);<br />
							//alert(filepath[x].Path);<br />
							x++;<br />
						<br />
							 <br />
							<br />
					}<br />
						 <br />
					<br />
<br />
                   <br />
               }<br />
          }<br />
     }<br />
	 <br />
	    // calls the sort function on the array<br />
	   	filepath.sort(sortDateModified);<br />
		for(i=0; i<x;i++){	<br />
			//outputs sorted results<br />
			result +=<br />
                         '<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +<br />
                         '<TD NOWRAP><FONT CLASS="find">&nbsp;<A TARGET="_blank" HREF="' +<br />
                         filepath[i].Path + '">' + filepath[i].name +<br />
                         '</A>&nbsp;</FONT></TD>' +<br />
                         '<TD NOWRAP><FONT CLASS="find"> ' + filepath[i].type + ' </FONT></TD>' +<br />
						 '<TD NOWRAP><FONT CLASS="find"> '+ filepath[i].DateLastModified +' </FONT></TD>' +<br />
                         '<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;' +<br />
                         toMetric( filepath[i].size )   + '&nbsp;</FONT></TD><TD><input type="Button" name=delete" class="formItem" value="Delete" onClick="deleteFile(&quot;'+ filepath[i].Path + '&quot;)"></TD></TR>'; <br />
						  <br />
						// Toggle the color toggle variable.<br />
                    	toggle = !toggle;<br />
		}<br />
	  <br />
}<br />
// filefunction holds values of multidem array for sorting and other functions<br />
function filefunction(path, Name, Type, datemodified, Size){<br />
			this.Path = path;<br />
			this.name = Name;<br />
			this.type = Type;<br />
			this.DateLastModified = datemodified;<br />
			this.size = Size;<br />
}<br />
<br />
// delete file function<br />
function deleteFile(fpath){<br />
var answer = confirm('Are you sure you want to delete '+fpath+'?');<br />
	if(answer){<br />
	var deleteobject;<br />
	deleteobject = new ActiveXObject("Scripting.FileSystemObject");<br />
	deleteobject.DeleteFile(fpath);<br />
	scan();<br />
	}else{}<br />
}<br />
<br />
// sort date function<br />
function sortDateModified(a, b) {<br />
    var x = b.DateLastModified;<br />
    var y = a.DateLastModified;<br />
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));<br />
}<br />
<br />
<br />
// Validates path and filename and initiates the file scan.<br />
function scan( ) {<br />
<br />
     // Parse filename and extention from the given mask.<br />
     FileName = ( frmSearch.txtMask.value.lastIndexOf( "." ) > -1 ) ? frmSearch.txtMask.value.slice( 0, frmSearch.txtMask.value.lastIndexOf( "." ) ) : ( frmSearch.txtMask.value.length > 0 ) ? frmSearch.txtMask.value.toLowerCase( ) : "*";<br />
     Extention = ( frmSearch.txtMask.value.lastIndexOf( "." ) > -1 ) ? frmSearch.txtMask.value.slice( frmSearch.txtMask.value.lastIndexOf( "." ) + 1 ).toLowerCase( ) : "*";<br />
<br />
     // Validate the given path.<br />
     if( frmSearch.txtPath.value.length > 0 && fso.FolderExists( frmSearch.txtPath.value ) ) {<br />
<br />
          // Path exists. Generate table headder.<br />
          result =<br />
               '<TABLE BORDER="0" WIDTH="100%" CELLPADDING="5"><TR>' +<br />
               '<TD WIDTH="60%" CLASS="title">Name</TD>' +<br />
               '<TD WIDTH="25%" CLASS="title">Type</TD>' +<br />
			   '<TD WIDTH="15%" CLASS="title">Last Modified</TD>' +<br />
               '<TD WIDTH="15%" CLASS="title">Size</TD>' +<br />
			   '<TD WIDTH="15%" CLASS="title">Delete File</TD></TR>';<br />
<br />
          // Collect valid filenames.<br />
          FindFile( fso.GetFolder( frmSearch.txtPath.value ) );<br />
<br />
          // Close and display search results table.<br />
          outPut.innerHTML = result + "</TABLE>";<br />
<br />
     } else {<br />
<br />
          // Path is invalid.   Alert user.<br />
          alert( "Please enter a valid Path before proceeding." );<br />
     }<br />
}<br />
<br />
<br />
</SCRIPT><br />
<br />
<br />
<br />
<BODY onLoad="frmSearch.txtMask.focus( ); frmSearch.txtMask.select( )" BGCOLOR="#ffffff" TOPMARGIN="0" LEFTMARGIN="0"><br />
<br />
<center><br />
<FORM ID="frmSearch" NAME="frmSearch"><br />
<br />
<TABLE BORDER="0" CELLPADDING="0" STYLE="border-collapse: collapse;" CELLPADDING="2"><br />
<TR><br />
     <TD><FONT FACE="Arial" SIZE="2"><B> Mask :&nbsp; </B></FONT></TD><br />
     <TD><INPUT TYPE="text" VALUE="*.*" ID="txtMask" NAME="txtMask" CLASS="formItem" STYLE="width:600;"></TD><br />
     </TR><br />
<TR><br />
     <TD><FONT FACE="Arial" SIZE="2"><B> Path :&nbsp; </B></FONT></TD><br />
     <TD><INPUT TYPE="text" VALUE="Y:\" ID="txtPath" NAME="txtPath" CLASS="formItem" STYLE="width:600;"></TD><br />
     </TR><br />
<TR><br />
     <TD>&nbsp;</TD><br />
     <TD><br />
          <INPUT TYPE="submit" VALUE="Search" CLASS="formItem" STYLE="width:150;"<br />
               onClick="scan( ); frmSearch.txtMask.focus( ); frmSearch.txtMask.select( ); return false;"><br />
          &nbsp; &nbsp; &nbsp;<br />
          <INPUT TYPE="checkbox" CHECKED ID="chkShowFolders" NAME="chkShowFolders"<br />
               ><LABEL FOR="chkShowFolders">Show sub-folders</LABEL>&nbsp;&nbsp;&nbsp;&nbsp;Older Than:<select name="form_date"><br />
			   <option value="6">6yrs</option><option value="5">5yrs</option><option value="4">4yrs</option><option value="3">3yrs</option></select><br />
          </TD><br />
     </TR><br />
<TR><br />
     <TD COLSPAN="2"><br />
          <BR> <FONT FACE="arial" SIZE="2"><B> Search Result: </B></FONT><br />
          <HR><br />
          <DIV ID="outPut"></DIV><br />
          </TD><br />
     </TR><br />
</TABLE><br />
<br />
</FORM><br />
<br />
</center><br />
</BODY></HTML>

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 
GeneralFinding files without using ActiveX Pin
Keertikiran15-May-07 21:09
Keertikiran15-May-07 21:09 
GeneralRe: Finding files without using ActiveX Pin
Uno198213-Aug-09 9:47
Uno198213-Aug-09 9:47 
Generala comment from nee_bhatia Pin
Sean Ewington8-May-07 3:29
staffSean Ewington8-May-07 3:29 
GeneralDisplay Files after Sorting. [modified] Pin
Keertikiran3-Apr-07 23:09
Keertikiran3-Apr-07 23:09 
GeneralRe: Display Files after Sorting. Pin
Uno19823-Apr-08 4:14
Uno19823-Apr-08 4:14 
QuestionActiveXObject("Scripting.FileSystemObject") in Mozilla Pin
megha.purkayastha29-Nov-06 2:08
megha.purkayastha29-Nov-06 2:08 
AnswerRe: ActiveXObject("Scripting.FileSystemObject") in Mozilla Pin
Uno198213-Aug-09 9:51
Uno198213-Aug-09 9:51 
GeneralFo is NULL or not an object [modified] Pin
Peter from Hungary21-Jun-06 2:49
Peter from Hungary21-Jun-06 2:49 
GeneralRe: Fo is NULL or not an object Pin
VijayashankarPalanichamy7-Oct-07 21:24
VijayashankarPalanichamy7-Oct-07 21:24 
GeneralRe: Fo is NULL or not an object Pin
Uno19823-Apr-08 10:13
Uno19823-Apr-08 10:13 

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.