Simple Text editor using File System Access API

20 Dec, 2020
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.
/* 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
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type