Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create txt file in javascript

Tags:

javascript

if (window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","t1.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
xmlhttp.open("w","t1.txt");
xmlhttp.writeln('hai');
xmlhttp.close();
console.log(xmlDoc);

I'll read t1.txt file using XMLHttpRequest(), How I'll write some more text in same file for t1.txt

like image 847
vijay Avatar asked Feb 22 '16 07:02

vijay


1 Answers

You can't. Browser-side javascript are not allowed to write to client machine without disabling a lot of security options.

Instead, you could download a new file using this code

function downloadContent(name, content) {
  var atag = document.createElement("a");
  var file = new Blob([content], {type: 'text/plain'});
  atag.href = URL.createObjectURL(file);
  atag.download = name;
  atag.click();
}

downloadContent("t1.txt","hello world");
like image 163
thanhpk Avatar answered Oct 22 '22 19:10

thanhpk