File Management In Javascript
Solution 1:
Writing a file is not a feature of Javascript. In some recent browsers you can already read them, but it's not a good option. The best way is to read it with PHP and get the response with XMLHttpRequest.
JavaScript
var xhr = XMLHttpRequest ? newXMLHttpRequest() : newActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
window.console.log(this.response);
}
xhr.open('GET','/fileReader.php?fileName=foo.txt');
xhr.send();
PHP
$content = file_get_contents($_GET['fileName']);
if($content)
echo$content;
elseecho"The file could not be loaded"
Solution 2:
If I understood your question correctly, you wish to read/write files in the server and your server side language is javascript. If you are using Node, this link : http://nodejs.org/api/fs.html#fs_fs_readfile_filename_encoding_callback provides relevant information on doing the same.
Solution 3:
You can read files by doing an AJAX request with possibly a file name or id
var xhr = XMLHttpRequest ? newXMLHttpRequest() : newActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
window.console.log(this.response);
}
xhr.open('GET','/readfile.php?id=1234');
xhr.send();
You can write the file by getting the data from possibly a input of type text. Assume the input id to be "text"
var xhr = XMLHttpRequest ? newXMLHttpRequest() : newActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
window.console.log(this.response);
}
xhr.open('POST','/write.php');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("id=someid&text=" + document.getElementById("text").value);
on the php side just get the post data and write that to the file
$id = $_REQUEST["id"];
$text = $_REQUEST["text"]
$file = fopen($id . ".txt","w"); // you can change w to a incase you want to append to existing content in the file
fwrite($file,$text);
fclose($file);
If you want Javascript to do the reading or writing, as far as my knowledge goes theres only a HTML5 File API but thats for reading files only I guess.
Post a Comment for "File Management In Javascript"