There are two ways to read and write a file using JavaScript
- Using JavaScript extensions
- Using a web page and Active X objects
Best answer
There are two ways to read and write a file using JavaScript
Answer: In a browser, JavaScript can read a file chosen by the user with the File API (FileReader) and "write" by offering a download; on the server, Node.js reads and writes files with the fs module.
For security, browser JavaScript cannot freely open files on the user's disk; the user must choose the file.
1. Reading a file in the browser
<input type="file" id="f">
<script>
document.getElementById("f").onchange = function () {
var reader = new FileReader();
reader.onload = function () {
console.log(reader.result); // file contents as text
};
reader.readAsText(this.files[0]);
};
</script>
2. Writing (saving) a file from the browser: create a Blob and let the user download it.
var blob = new Blob(["Hello file"], {type: "text/plain"});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "note.txt";
a.click();
3. Reading and writing with Node.js (server side):
const fs = require("fs");
fs.writeFileSync("data.txt", "Hello"); // write
const text = fs.readFileSync("data.txt", "utf8"); // read
console.log(text);
Older answers mention ActiveX objects (FileSystemObject); these worked only in old Internet Explorer and are no longer used.
Log in or create a free account to answer this question.