FILING WITH JAVASCRIPT Filing operations are not native to Javascript. However, in desktop applications, ActiveX can be used in conjuction with Javascript. All the normal file operations, reading/writing/appending data, creating folders, setting attributes, etc can be done with Internet Explorer and Windows. A useful file-listing function is also shown.
These functions provide access to folders and files. They use JScript 3.0 & ActiveX. Global Variables needed for filing:
gFile = ''; // Global gpath = ''; // Global - set this prior to calling the function, eg, "C:\\Folder01\\Folder02\\mydata.txt" fso = new ActiveXObject("Scripting.FileSystemObject"); ForWriting = 2; ForReading = 1; ForAppending=8; CreateIt = true; AsciiMode = 0; function OpenFile(Action) { if((Action==ForReading)&&(fso.FileExists(gpath))) { gFile = fso.OpenTextFile(gpath,ForReading,false,AsciiMode); } else { if (Action == ForWriting) { gFile = fso.OpenTextFile(gpath,ForWriting,CreateIt,AsciiMode); } else{ if((Action==ForAppending)&&(fso.FileExists(gpath))) { gFile=fso.OpenTextFile(gpath,ForAppending,false,AsciiMode); } } } function DeleteFile() { if (fso.FileExists(gpath)) { var afile = fso.GetFile(gpath); afile.Attributes[0]; afile.Delete();} } function CopyFile(FromFile,ToFile,overwrite) { // Set overwrite to true or false; FromFile, etc = full paths var f = fso.GetFile(FromFile); f.Attributes[0]; f.Copy(ToFile,overwrite); } function MakeFolder(NewFolderName,DesiredPath){ NewFolderName = fso.CreateFolder(DesiredPath); // 'DesiredFolderPath' : e.g., "C:\\MainFolder\\NewFolderName". } function DeleteFolder(){ // where gpath = full folder path if (fso.FolderExists(gpath)) {var afolder = fso.GetFolder(gpath); afolder.Delete();} } function CopyFolder(FromFolder,ToFolder,overwrite) { // where FromFolder, etc = full folder paths var f = fso.GetFolder(FromFolder); f.Copy(ToFolder,overwrite); } // The ListFile function is helpful if you want to have an array of file-names or last-modified dates, etc:
function ListFile(ThePath,TheArr,Ext){ // Builds an array of found file-names in ThePath folder. var filName='*'; var i=0; if(ThePath.length>0 && fso.FolderExists(ThePath)){ var foldName=fso.GetFolder(ThePath); var eNum=new Enumerator(foldName.Files); for(var i=0;!eNum.atEnd();eNum.moveNext()){ if((filName=="*")||(eNum.item().name.slice(0,eNum.item().name.lastIndexOf(".")).toLowerCase().indexOf(filName)>-1)){ if((Ext=="*")||(eNum.item().name.slice(eNum.item().name.lastIndexOf(".")+1).toLowerCase().indexOf(Ext)>-1)){ TheArr[i]=eNum.item().name; // Builds array of file names found i++; } } } } }
// Use ListFile thus: var tArr=new Array(); var gpath='C:\\BlahBlah'; ListFile(gpath,tArr,'csv'); // List the .csv files, for instance
// sort tArr with SortIt(tArr) var FileDate=Date.parse(fso.GetFile(gpath).DateLastModified); // get Last Modified Date of a file
Top
|