Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I write counter code that works from a local or network text file?

Counter Code

How do I write counter code that works from a local or network text file?

by  BillyRayPreachersSon  Posted    (Edited  )
This code will enable users (IE only - sorry!) to have a local counter that runs on their PC. It requires the FileSystemObject ActiceX control be allowed to run.

Code:
<html>
<head>
	<script type="text/javascript">
	<!--
		var fsObj = null;						// holds a pointer to the FileSystemObject
		var counter = 0;						// holds the counter value
		var counterFile = 'C:\\jsCounter.txt';	// holds the path and filename to the counter text file

		// returns 0 if no counter or NaN is found, the counter value otherwise
		function readCounter() {
			try {
				if (!fsObj.FileExists(counterFile))	return(0);
				var tempValue = fsObj.OpenTextFile(counterFile, 1).ReadLine();
				if (isNaN(tempValue) || tempValue == ' || tempValue == null) return(0);
				return(tempValue);
			}
			catch (err) {
				return(0);
			}
		}

		// returns false if write failed, true otherwise
		function writeCounter(counterValue) {
			try {
				//alert(counterValue);
				var counterFileObj = fsObj.OpenTextFile(counterFile, 2, true);
				counterFileObj.WriteLine(counterValue);
				counterFileObj.Close();
				return(true);
			}
			catch (err) {
				return(false);
			}

		}

		function init() {
			try {
				this.fsObj = new ActiveXObject('Scripting.FileSystemObject');
			}
			catch (err) { }

			if (!this.fsObj) {
				alert('You must allow the ActiveX object to load for the counter to work');
			} else {
				counter = readCounter();
				alert('Current counter: ' + counter);
				counter++;
				if (!writeCounter(counter)) alert('There was an error writing the counter');
			}
		}
	//-->
	</script>
</head>

<body onload="init();">
</body>
</html>

The file in the demo is a local file, but the path can be anything which resolves, like a network share, etc.

Enjoy!

Dan


[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top