Saving files

In this section, we are going to provide support for saving files. Similar to the Open file functionality, web developers need to perform some easy workarounds to invoke the file download feature from the code.

The most popular way to do this is to dynamically create an invisible hyperlink element with the download attribute set to the filename and then invoke a click. This is what we are going to implement for our project. Follow these steps to get started:

  1. Update the code in the Editor.js file and add the saveFile function, as shown in the following code:
const saveFile = contents => {
const blob = new Blob([contents], { type: 'octet/stream' });
const url = window.URL.createObjectURL(blob);

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
a.href = url;
a.download = 'markdown.md';
a.click();

window.URL.revokeObjectURL(url);
document.body.removeChild(a);
};

We have just created a helper function, saveFile(contents), that takes a string value as input and invokes a file download called markdown.md.

To make the saveFile function work, we are going to use the URL.createObjectURL API, which is supported by all web browsers. This static method allows us to create a URL object with the content of the file embedded into it. Then, you pass that URL to a dynamic hyperlink element and invoke the click event.

You can find out more about the URL.createObjectURL static method at https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL.
  1. Now, it's time to reuse the function we have just created. Update the editorDidMount function in order to invoke the saveFile upon clicking Cmd + S (or Ctrl + S):
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, () => {
const code = editor.getModel().getValue();
saveFile(code);
});

  1. Run the application and try saving the file with the keyboard combinations we have just provided. Notice that the browser automatically changes its name if you download the file more than once:

This is the traditional behavior of browsers.

There is a difference, however, if you run the same code in the Electron shell. By default, Electron asks you where you want to put the file upon clicking Cmd + S (or Ctrl + S):

At this point, you've got the Save and Open functionality working. This should allow you to work on multiple documents and make backup copies of the files.

Next, we will introduce application menu integration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset