I am a novice-intermediate programmer taking a stab at AJAX. While reading up on JavaScript I found it curious that most of the examples I've been drawing on use PHP for such an operation. I know many of you may argue that 'I'm doing it wrong' or 'JavaScript is a client-side language' etc. but the question stands. . .can you write a file in only JavaScript?
To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code. To write file to local, it's impossible to write it directly using JavaScript.
The possible ways to create and save files in Javascript are: Use a library called FileSaver – saveAs(new File(["CONTENT"], "demo. txt", {type: "text/plain;charset=utf-8"})); Create a blob object and offer a “save as”.
The short answer is no, because of the secure sandboxing the browser does around the HTML + JavaScript.
No. You could use JavaScript to create an AJAX request to a server-side processing script, but allowing JS to directly write to disk - either client-side or server-side - would be a massive, nasty, glaring, unforgivable browser security hole.
Yes, of course you can. It just depends on what API objects your javascript engine makes available to you.
However, odds are the javascript engine you're thinking about does not provide this capability. Definitely none of the major web browsers will allow it.
You can write cookies with Javascript, on newer browsers you also have an SQLite database to store client side data. You cannot store data in an arbitrary location on the disk though.
You can use something like Google Gears to produce JS applications which are capable of storing data in a local cache or database. You can't read or write arbitrary areas of the disk though. (This was written in 2009 - Google Gears is now deprecated)
These days, you should be looking at the local storage capabilities provided by HTML5
The short answer is no; you cannot by default write a file to the local disk, by using plain JavaScript in a browser. You'll need a helper to do that. For example, TiddlyWiki is a wiki engine that is just a single, static HTML file, but it can write itself to disk with the help of a Java applet (Tiddly Saver).
You can in Windows Scripting Host.
Next version of chrome (v52) made this possible with fetch api + service worker + streams, you can enable streams now with a flag...
you can go to the StreamSaver.js to see some examples of how to use it.
You can do something like this:
const writeStream = fs.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")
writeStream.write(uint8array)
writeStream.close()
Or just go ahead and look at the demos: https://jimmywarting.github.io/StreamSaver.js/example.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With