JavaScript write to text file

This page discusses - JavaScript write to text file

JavaScript write to text file


In this section, we are going to create a file and write text into it using JavaScript.

In the given example, firstly we have created an ActiveXObject object which is used to enable and return a reference to an Automation object and  used it with the CreateTextFile(), a JavaScript method , which generates a file specified and returns a TextStream object to read from or write to the file. The Boolean value defined in this method indicates whether to overwrite an existing file. Then, in order to write the text into the created file, we have used WriteLine() method. This code works only on Internet Explorer.

Syntax of ActiveXObject object:

var newObject = new ActiveXObject(servername.typename[, location])

The Active object takes three parts:
-  the name of the application providing the object. It is required.
typename -  the type or class of the object to create.
location - the name of the network server where the object is to be created.

 Here, we have taken servername as 'Scripting' and typename as 'FileSystemObject':

Here is the code:

<h2>Create Text file in JavaScript</h2>
function createFile(){
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.CreateTextFile("C:\\Hello.txt", false);
file.WriteLine('Hello World');
file.WriteLine('Hope is a thing with feathers, that perches on the soul.'); 
<input type="Button" value="Create File" onClick='createFile()'>

Output will be displayed as:

Download Source Code: