File management in Javascript

2019-09-21 05:30发布

问题:

How to write to a file in Javascript(on server)?

I also need to read the file. And here is my code:

function write()
{
var = true;
if( var = true)
{
//write file
    }
}
function read()
{
//read file
}

回答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 ? new XMLHttpRequest() : new ActiveXObject('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;
else echo "The file could not be loaded"


回答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.



回答3:

You can read files by doing an AJAX request with possibly a file name or id

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('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 ? new XMLHttpRequest() : new ActiveXObject('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.