Programming‎ > ‎

JScript

JScript Tips

Here are JScript tips. I'm using WSH with JScript to run performance test under Windows. I need some tricks to do what I want.

Index


How can I check a directory existence?

  
  // create filesystem object first  
  var fso;  
  fso = new ActiveXObject("Scripting.FileSystemObject");  
  if (!fso.FolderExists(dirname))  
  {    
    WScript.Echo(dirname + " does not exist");    
	WScript.Quit();  
  }
  

Top


How can I check a file existence?

  
  // create filesystem object first  
  var fso;  
  fso = new ActiveXObject("Scripting.FileSystemObject");  
  if (!fso.FileExists(filePathName))  
  {    
    WScript.Echo(filePathName + " does not exist");    
	WScript.Quit();  
  }
  

Top


How can I create a directory including its path?

I needed a directory to put output but if that directory does not exist, I need to create one including the path to that directory.

  
  // generic routine to check dirName exists   
  // if not exists, create that dir and path above  
  function dirtree(dirName)  
  {    
    var fso;    
	fso = new ActiveXObject("Scripting.FileSystemObject");    
	if (!fso.FolderExists(dirName))    
	{      
	  // split dirname into components      
	  aFolders = dirName.split("\\");      
	  // the root      
	  newFolder = fso.BuildPath(aFolders[0],"\\");      
	  WScript.Echo(newFolder + " ");      
	  for (i=1; i < aFolders.length; ++i)      
	  {        
	    newFolder = fso.BuildPath(newFolder, aFolders[i]);        
		if (!fso.FolderExists(newFolder))        
		{	  
		  try	  
		  {	    
		    fso.CreateFolder(newFolder);	    
			WScript.Echo(newFolder+" is created");	  
		  }	  
		  catch(e)	  
		  {	    
		    msg = "error in creating output directory";	    
			WScript.Echo(msg);	    
			WScript.Quit();	  
		  }        
		}        
		else	  
		  WScript.Echo(newFolder + " exists");      
	  }    
	}  
  }
  

Top


How can I replace one extension with another for a filename?

I needed a way to create a filename with different extension so that I can relate two files. Here is the example of .bmp with .ntg.

  
  // .bmp is replaced with ext  
  // e.g. replaceBmp(iniName, ".ntg");  
  function replaceBmp(iniName, next)  
  {    
    // regexp  g = global, i = case insensitive    
	var re = new RegExp("\.bmp","i");    
	nName = new String(iniName);    
	pos = nName.search(re);    
	nName = nName.substring(0, pos);    
	nName += next;    
	return nName;  
  }
  

Top


How can I get the timestamp?

 
  var dateObject = new Date() 
  WScript.Echo("time is " + dateObject.toLocaleString());
  

Top

Home

Updated 8/30/2008