Category: Tech Talk

Write files using javascript

The following piece of javascript when run from Internet Explorer will write a file on to your desktop.

<script>
function WriteToFile(fileName,text)
{
var fso = new ActiveXObject(”Scripting.FileSystemObject”);
try{
//Open a file for writing. It will generate an error if it exists
var s = fso.CreateTextFile(fileName, false);
s.WriteLine(text);
s.Close();
} catch(err)
{
//If a file exisits, append to it
var s = fso.OpenTextFile(fileName, 8);
s.WriteLine(text);
s.Close();
}
}
</script>

This won’t work if:
1. You’re using a non-IE browser (which doesn’t support activex objects)
2. You’re using an IE browser on an XP machine with SP2 installed and the activex object is being blocked