Simple Text Editor using File System Access API
Last Updated :
31 Jul, 2023
In this article, we will create a simple text editor like application that we can use to open, edit, and save text files with the help of File System Access API.
File System Access API enables us to interact with files on our local devices like photo and video editors. When the user gives permission, this helps us to read or save changes directly to files and folders on the local storage. Using this API we can read, write, modify, and also we can open a directory to modify its content.
We will create this application in three steps.
- Make a general structure using HTML.
- Give a general style using CSS.
- Writing some code in JavaScript with the help of File System Access API.
HTML code: We will use HTML to design the web page structure or layout. Create a container with a text area and two buttons to open the file and save the file.
HTML
<!DOCTYPE html>
<html>
<body>
<div class="container">
<!--Text Area -->
<textarea id="content"
placeholder="Lets Write ">
</textarea>
<!--Buttons -->
<div class="buttons">
<!--To open -->
<button id="openfile">
Open
</button>
<!-- To save-->
<button id="savefile">
Save
</button>
</div>
</div>
</body>
</html>
CSS code: CSS is used to give general styling and make it more visually appealing. Give general styling to the whole page like color and alignment. We use flex to center the elements. Include the following in the above HTML code in the style section of the head part of the code.
CSS
/* General Alignment to container
using flexbox */
.container{
display: flex;
height: 100vh;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
/* Styling to the textarea */
textarea {
width: 90vw;
color: #777;
font-size: 1.1rem;
min-height: 20rem;
border: 2px dashed rgba(0, 0, 0, 0.2);
padding: 1.5rem;
}
/* Aligning buttons to center */
.buttons{
width: 100%;
display: flex;
justify-content: center;
}
/* General styling to button */
button{
margin:0 0.5rem;
font-size: 1.1rem;
font-weight: 800;
background-color: blue;
color: #ffffff;
padding: 1rem 1.5rem;
}
Output:
JavaScript: We will use filesystem API to open, edit, and save the file. We will break our JavaScript code into three steps.
- Creating variables and get access to elements with id, open files, and save the file.
- To create a function to open the file.
- To create a function to close the file
Step 1: Getting access to the elements
HTML
const openFile = document.getElementById('openfile');
const saveFile = document.getElementById('savefile');
const contentTextArea = document.getElementById('content');
let fileHandle;
Step 2: It demonstrates a function to open the file. To open a file, first we need to prompt the user to select a file. For this, we will use the showOpenFilePicker() method. This method will return an array of filehandles.
Now we have a filehandle, so we can access the file itself by using the method filehandle.getFile() it returns the file object, which contains a blob. To access the data we will use method text().
HTML
const open = async () => {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
contentTextArea.value = contents;
}
Step 3: It demonstrates the function to save the file. To save the file we will use the showSaveFilePicker() method. We also want to save it in .txt format, so we will provide some optional parameters.
Now we have to write the file on a disk for this we will use the FileSystemWritableFileStream object. We will create a stream by calling the createWritable() method. When this method is called, it will check for write permission if permission is not given it will ask the user for permission. If permission is denied, it will throw an exception. Then we will write the contents of the file to the stream using the write() method. We will close the writable stream and will return the handle.
HTML
const save = async content => {
try {
const handle = await window.showSaveFilePicker({
types: [
{
accept: {
'text/plain': ['.txt'],
},
},
],
})
// Create a FileSystemWritableFileStream to write
const writable = await handle.createWritable();
// Write the contents of the file to the stream
await writable.write(content);
// Close the file and write the contents to disk
await writable.close();
return handle;
} catch (err) {
console.error(err.name);
}
}
At the end, we will associate the open and save method to our variable open file and save file.
HTML
openFile.addEventListener('click', () => open());
saveFile.addEventListener('click',
() => save(contentTextArea.value));
Output: So our editor is ready now.
https://github.com/Nandini-72/Notepad
Similar Reads
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Sliding Window Technique
Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
Domain Name System (DNS)
DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read