Writing data to a local text file using javascript

I created a procedure for writing content to a text file on my local machine.

<form id="addnew"> <input type="text" class="id"> <input type="text" class="content"> <input type="submit" value="Add"> </form> <script> jQuery(function($) { $('#form_addjts').submit(function(){ writeToFile({ id: $(this).find('.id').val(), content: $(this).find('.content').val() }); return false; }); function writeToFile(data){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.OpenTextFile("D:\\data.txt", 8); fh.WriteLine(data.id + ',' + data.content); fh.Close(); } }); </script> 

This works great and allows me to add my new data to a file.

But I want to update a specific CONTENT line based on the identifier I am passing.
I searched a lot, but could not find.

How to update a specific line in a file based on identifier?

Note. - I do not use the server as such. I have an html file (contains all the functions) that I will run on my local machine.

+7
javascript jquery html file-io hta
source share
1 answer

Our HTML:

 <div id="addnew"> <input type="text" id="id"> <input type="text" id="content"> <input type="button" value="Add" id="submit"> </div> <div id="check"> <input type="text" id="input"> <input type="button" value="Search" id="search"> </div> 

JS (write to txt file):

 function writeToFile(d1, d2){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.OpenTextFile("data.txt", 8, false, 0); fh.WriteLine(d1 + ',' + d2); fh.Close(); } var submit = document.getElementById("submit"); submit.onclick = function () { var id = document.getElementById("id").value; var content = document.getElementById("content").value; writeToFile(id, content); } 

checking a specific line:

 function readFile(){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.OpenTextFile("data.txt", 1, false, 0); var lines = ""; while (!fh.AtEndOfStream) { lines += fh.ReadLine() + "\r"; } fh.Close(); return lines; } var search = document.getElementById("search"); search.onclick = function () { var input = document.getElementById("input").value; if (input != "") { var text = readFile(); var lines = text.split("\r"); lines.pop(); var result; for (var i = 0; i < lines.length; i++) { if (lines[i].match(new RegExp(input))) { result = "Found: " + lines[i].split(",")[1]; } } if (result) { alert(result); } else { alert(input + " not found!"); } } } 

Put them inside the .hta file and run it. Tested on W7, IE11. It works. Also, if you want me to explain what is happening, say it.

+10
source share

All Articles