PDA

View Full Version : Javascript and Active-X Append Text File



Basscyst
Aug 29th, 2003, 01:15 AM
Quick Question, I have a script that uses javascript and activeX to write text files to a local drive. Is it possible to append that text file (add a line of info - to the last line of the text) dynamically? Using Active-X and Javascript. I am well aware of the other ways of doing this. But do to certain restricitons it is not an option.

Thanks in advance,
Basscyst

Graeme Hackston
Aug 29th, 2003, 02:06 AM
I thought WriteLine() does this but when I tried it just re-wrote the whole file.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/jsmthWriteLine.asp

So I opened the file, added the string then wrote over the whole file. It works but I noticed another assumption of mine is wrong. The line break "\n" works in my text editor but doesn't in NotePad. There must be another way to write a line break.


var the_file = 'C:\\test.txt', TristateFalse = 0, ForWriting = 2
var fso = new ActiveXObject("Scripting.FileSystemObject")
var fs = fso.OpenTextFile(the_file)
var str = fs.ReadAll()
fs.Close()
str += '\nAnother line'
fs = fso.GetFile(the_file)
fs = fs.OpenAsTextStream(ForWriting, TristateFalse)
fs.Write(str)
fs.Close()

brothercake
Aug 29th, 2003, 02:34 AM
Originally posted by Graeme Hackston
The line break "\n" works in my text editor but doesn't in NotePad. There must be another way to write a line break.
Maybe "\r" (for a carriage-return) would work?

Graeme Hackston
Aug 29th, 2003, 02:46 AM
That's the trick brothercake. Combining them works in both.


str += '\r\nAnother line'

Roelf
Aug 29th, 2003, 07:14 AM
if you open the file like this:


var fs = fso.OpenTextFile(the_file, 8)

you append to the file, second argument of the openfilemethod is the iomode, can have tree values:
1 - read only
2 - overwrite
8 - append

so there wont be the need to read the entire file, add something to the variabele and then overwrite the file again.

Graeme Hackston
Aug 29th, 2003, 07:19 AM
Cool, thanks Roelf

Basscyst
Aug 29th, 2003, 07:11 PM
Hey Thanks All! That is just what I was looking for. We'll see how it pans out. :-)