Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

How can we read and write a file using JavaScript

Posted on May 3, 2017August 4, 2020 by Habibie

Basically, JavaScript can not read and write a file. But it should be clearer: JavaScript can not read and write a file “on server”. What about on client side? Yes, JavaScript can read and write file on client side.

Here I share HTML and JavaScript code that can perform (a sort of) file read and write on client machine.

<!DOCTYPE html>
<html>
<head>
	<title>JavaScript read and write a file</title>
</head>
<body>
    <h1>Select a file to read:</h1>
    <p>First, pick a file, for example a text file with any text in it.</p>
	<input type="file" id="myFile">
	<p>Then click Read button to read the file's content.</p>
    <button onclick="loadFileAsText()">Read</button><br />
	<h1>Content of loaded file</h1>
	<textarea id="inputTextToSave"></textarea> <br />
	<p>You can modify above text and save it using below button.</p>
	<h1>Save the file</h1>
	<button onclick="savefile()">Save</button>
	<p id="dlink">Click save button to generate download link.</p>
	<script>
	function loadFileAsText(){
	  var myFile = document.getElementById("myFile").files[0];

	  var fileReader = new FileReader();
	  fileReader.onload = function(fileLoadedEvent){
		  var textFromFileLoaded = fileLoadedEvent.target.result;
		  document.getElementById("inputTextToSave").value = textFromFileLoaded;
	  };

	  fileReader.readAsText(myFile, "UTF-8");
	}
	function savefile(){
		var content = document.getElementById("inputTextToSave").value;
		uriContent = "data:application/octet-stream," + encodeURIComponent(content);
		document.getElementById("dlink").innerHTML = "<a href=" + uriContent + " download=\"savedfile.txt\">Here is the download link</a>";
	}
	</script>
</body>   
</html>

And here is the live result:

Post Views: 487
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Hover Reveal script for Unity to show and hide object on mouse hover
  • How to Prevent UI Clicks in Unity from “Bleeding Through” to 3D Objects Behind Them
  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
© 2026 ThirteeNov | Powered by Superbs Personal Blog theme