Reputation: 239
I am learning javascript and so I was trying to append a string to a text file using Javascript. I tried the following but for some reason nothing happens. Where could I be doing wrong ? I am running the code on Mozilla firefox browser.
<%--
Document : demo
Created on : 17 Nov, 2016, 11:01:01 AM
Author : user
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<button onclick="WriteFile()">Click me</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
function WriteFile()
{
var fh = fopen("C:\\javascriptlogs\\myfile.txt", 3); // Open the file for writing
if(fh!=-1) // If the file has been successfully opened
{
var str = "Some text goes here...";
fwrite(fh, str); // Write the string to a file
fclose(fh); // Close the file
}
}
</script>
</body>
</html>
Upvotes: 0
Views: 1255
Reputation: 2540
fopen
, fwrite
, fclose
, are not defined browser JavaScript functions, and browser JavaScript does not have direct access to the local computer's file system by design. If it did, any website could read files from your computer -- that would be pretty worrisome as most people have personal stuff stored there!
You could use node.js to do this, but wouldn't run in the browser.
Upvotes: 2
Reputation: 4125
Unfortuanlly, JavaScript doesn't have a fopen
function like known from other programming languages. Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
This is a little example that may get you started.
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Upvotes: 2