最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I write to file using XMLHttpRequest - Stack Overflow

programmeradmin1浏览0评论

I'm using XMLHttpRequest to read the file.

Can I write to file using XMLHttpRequest or any other javascript method and how do I do that?

Currently in my application I'm using PHP for this purpose, but I need not to use it.

function readTextFile(path, callback) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.responseXML);
        } else {
          reject(xhr);
        }
      }
    };
    xhr.open("GET", path);
    xhr.send();
  });
}
$(document).ready(function() {
  readTextFile("device.xml")
    .then(function(fileData) {
      // Use the file data
    })
    .catch(function(xhr) {
      // The call failed, look at `xhr` for details
    });
});

I'm using XMLHttpRequest to read the file.

Can I write to file using XMLHttpRequest or any other javascript method and how do I do that?

Currently in my application I'm using PHP for this purpose, but I need not to use it.

function readTextFile(path, callback) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.responseXML);
        } else {
          reject(xhr);
        }
      }
    };
    xhr.open("GET", path);
    xhr.send();
  });
}
$(document).ready(function() {
  readTextFile("device.xml")
    .then(function(fileData) {
      // Use the file data
    })
    .catch(function(xhr) {
      // The call failed, look at `xhr` for details
    });
});
Share Improve this question edited Jan 4, 2018 at 13:53 mplungjan 178k28 gold badges181 silver badges240 bronze badges asked Jan 4, 2018 at 13:46 Vaxo BasilidzeVaxo Basilidze 1,05716 silver badges37 bronze badges 5
  • You can use any other server side language, you wont be able to pull it off with only client side code – Luca Kiebel Commented Jan 4, 2018 at 13:53
  • Also if you use jQuery why not use the vastly simpler $.ajax.done instead of XMLHttpRequest and promise? – mplungjan Commented Jan 4, 2018 at 13:53
  • @mplungjan Are they cross browser? – Vaxo Basilidze Commented Jan 4, 2018 at 13:55
  • yes, they are... – Luca Kiebel Commented Jan 4, 2018 at 13:56
  • Certainly more than plain XMLHttpRequest depending on jQuery version – mplungjan Commented Jan 4, 2018 at 13:59
Add a ment  | 

5 Answers 5

Reset to default 2

JavaScript in a Browser can't write to files. At least not in any useful way, or cross platform. Chrome has a filesystem api in the browser but it is not officially supported, nor will it ever be.

https://www.html5rocks./en/tutorials/file/filesystem/

XMLHttpRequest is read-only so to say. It is as it's name suggests, it makes a request.

You could however make a XMLHttpRequest to a backend server running PHP or NodeJs that could write to a file.

If you do not like PHP and prefer JavaScript, then NodeJs is nice.

NodeJS example:

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

https://nodejs/docs/latest/api/fs.html

Can I write to file using XMLHttpRequest or any other javascript method and how do I do that?

No you can not! JavaScript is client-side programming language, that means it can't edit files on other puter or server.

You need server and server-side programming language like PHP or any other because it's really server writing in files not you - you just ask it to do so with requests.

You can make HTTP requests with XMLHttpRequest.

If you want to write to a file, then the server needs to be set up to recognise that some kinds of request should result in data being written to a file.

This normally requires the use of a server-side programming language, such as PHP (which you've rejected).

You could also look at WebDav, for which there is at least one JavaScript library which wraps XMLHttpRequest.

When you use a simple HTTP method like plain GET against a web server, the server would give you the file - no problem there.

Now when you want to write data to the server, you have to tell the server that you would like to write some data to the file system. You will have to create an application in the web server using PHP, NodeJs etc to handle such a request and write data as a file into the file system.

There are no alternatives to this method as long as your server use standard HTTP for munication.

Hi, if you want to use just js and to write a file using it, it is possible, but you need a server code (made in Node.Js). So here is the code:

Server [main.js]

var http = require('http');
var util = require('util');
var querystring = require('querystring');
var fs = require('fs');
var filename = 'your_file.txt';
var port = '80';



var server = http.createServer(function(req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    if (req.method == 'GET') {
        res.write(fs.readFileSync('index.html', 'utf8'));
        res.end();
    } else {

        var chunk = '';
        req.on('data', function(data) {
            chunk += data;
        });
        req.on('end', function() {
            console.log(chunk);
            fs.readFile(filename, 'utf-8', function(err, data) {

                if (!err) {
                    fs.writeFile(filename, data + '\n' + chunk, (err) => {
                        if (err) {
                            throw err;
                        }
                    });
                } else {
                    throw err;
                }
            });
            //any function to perform on clint side webpage.
            res.end();
        });

    }
}).listen(port);
console.log('Successfully started serving at : ' + port);

Client WebPage [index.html]

<!DOCTYPE html>
<html>
<body>

<button onclick="check()">Send!</button>
<input type="text" placeholder="enter some message here">

<script>
function check() {
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.open("post", "#", true);
  xhttp.send(document.querySelector('input').value);
}
</script>

</body>
</html>

  • All the files are uploaded.
  • Note: Please make it sure that your folder already has the file to be written.
  • Usage: node main.js.
发布评论

评论列表(0)

  1. 暂无评论