Skip to content
doubtly

2 answers

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.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.