Click here to Skip to main content
15,886,110 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.2K   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: What happened??? Pin
harikagupta4-Oct-07 20:13
harikagupta4-Oct-07 20:13 
GeneralDocumentation Pin
jajansse12-Aug-04 23:05
jajansse12-Aug-04 23:05 
GeneralRe: Documentation Pin
oregano20-Jul-05 17:54
oregano20-Jul-05 17:54 
GeneralRunning this code in a client Pin
Severedlimb24-Jun-03 8:37
Severedlimb24-Jun-03 8:37 
GeneralRe: Running this code in a client Pin
Anonymous20-Jul-05 8:52
Anonymous20-Jul-05 8:52 
GeneralInclude Sub Directory Pin
AFShin Dehghani26-Mar-02 5:50
AFShin Dehghani26-Mar-02 5:50 
GeneralRe: Include Sub Directory Pin
francisco cespedes6-Mar-03 9:48
francisco cespedes6-Mar-03 9:48 
GeneralRe: Include Sub Directory Pin
oregano20-Jul-05 18:04
oregano20-Jul-05 18:04 
Here's my update to the original download. I recently decided that I would like to be able to use a web page to scan through a folder structure and this is what I came up with.

I can't post attachments so I'm going to include the complete code as I have it to date. I've annotated it to death so it might be easier to follow what's going on. Copy and paste to Notepad and save as SEARCH.HTA. This makes it a HyperText Application and gets rid of the active scripting warnings.

A special thanks to AFShin Dehghani for his original code!



<HTML><HEAD><TITLE> Search... with sub-folders!
</TITLE></HEAD>



<STYLE>

.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 LANGUAGE="JavaScript">


// Establish a few environment variables.
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
var result = new String( );
var FileName = new String( );
var Extention = new String( );


// 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;

// If chkShowFolders is checked, display the sub-folders.
if( frmSearch.chkShowFolders.checked ) {

// Check to see if the current folder is the drive root.
if( fso.GetParentFolderName( frmSearch.txtPath.value ).length > 0 ) {

// Add the parent folder to the table result string.
result +=
'<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +
'<TD NOWRAP><FONT CLASS="find">&nbsp;<A HREF="#" onClick="subFolder( \'' +
escape( fso.GetParentFolderName( frmSearch.txtPath.value ) ) +
'\' ); return false;">..</A>&nbsp;</FONT></TD>' +
'<TD NOWRAP><FONT CLASS="find"> Parent folder </FONT></TD>' +
'<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;</FONT></TD></TR>';

// Toggle the color toggle variable.
toggle = !toggle;
}

// Establish enumerator to step from folder to folder in the SubFolders collection.
var folderEnum = new Enumerator( searchPath.SubFolders );

// Iterate through the folders in the collection.
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( );

// Add the folder to the table result string.
result +=
'<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +
'<TD NOWRAP><FONT CLASS="find">&nbsp;<A HREF="#" ' +
'onClick="subFolder( \'' + escape( folder.Path ) + '\' ); return false;">' + folder.name +
'</A>&nbsp;</FONT></TD>' +
'<TD NOWRAP><FONT CLASS="find"> ' + folder.type + ' </FONT></TD>' +
'<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;</FONT></TD></TR>';

// Toggle the color toggle variable.
toggle = !toggle;
}
}

// 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.
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.
result +=
'<TR' + ( ( toggle ) ? '' : ' BGCOLOR="#f0f0f0"' ) + '>' +
'<TD NOWRAP><FONT CLASS="find">&nbsp;<A TARGET="_blank" HREF="' +
file.Path + '">' + file.name +
'</A>&nbsp;</FONT></TD>' +
'<TD NOWRAP><FONT CLASS="find"> ' + file.type + ' </FONT></TD>' +
'<TD NOWRAP ALIGN="right"><FONT CLASS="find">&nbsp;' +
toMetric( file.size ) + '&nbsp;</FONT></TD></TR>';

// Toggle the color toggle variable.
toggle = !toggle;
}
}
}
}



// 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 ) ) {

// Path exists. Generate table headder.
result =
'<TABLE BORDER="0" WIDTH="100%" CELLPADDING="0"><TR>' +
'<TD WIDTH="60%" CLASS="title">Name</TD>' +
'<TD WIDTH="25%" CLASS="title">Type</TD>' +
'<TD WIDTH="15%" CLASS="title">Size</TD></TR>';

// 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">


<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="C:\" ID="txtPath" NAME="txtPath" CLASS="formItem" STYLE="width:600;"></TD>
</TR>
<TR>
<TD>&nbsp;</TD>
<TD>
<INPUT TYPE="submit" VALUE="Search" CLASS="formItem" STYLE="width:150;"
onClick="scan( ); frmSearch.txtMask.focus( ); frmSearch.txtMask.select( ); return false;">
&nbsp; &nbsp; &nbsp;
<INPUT TYPE="checkbox" CHECKED ID="chkShowFolders" NAME="chkShowFolders"
><LABEL FOR="chkShowFolders">Show sub-folders</LABEL>
</TD>
</TR>
<TR>
<TD COLSPAN="2">
<BR> <FONT FACE="arial" SIZE="2"><B> Search Result: </B></FONT>
<HR>
<DIV ID="outPut"></DIV>
</TD>
</TR>
</TABLE>

</FORM>


</BODY></HTML>

GeneralRe: Include Sub Directory Pin
248912831-Aug-06 20:40
248912831-Aug-06 20:40 
GeneralRe: Include Sub Directory Pin
meghak6-Apr-07 17:16
meghak6-Apr-07 17:16 
GeneralRe: Include Sub Directory Pin
bitlisz4-Sep-07 5:36
bitlisz4-Sep-07 5:36 
GeneralRe: Include Sub Directory Pin
harikagupta3-Oct-07 0:43
harikagupta3-Oct-07 0:43 
GeneralRe: Include Sub Directory Pin
Arun Jacob16-Dec-07 18:15
Arun Jacob16-Dec-07 18:15 
GeneralRe: Include Sub Directory Pin
Uno198214-Mar-08 18:33
Uno198214-Mar-08 18:33 
GeneralRe: Include Sub Directory Pin
panterall19-Jun-12 8:53
panterall19-Jun-12 8:53 

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.