Search code examples
typescriptmonaco-editorlanguage-server-protocol

How can I save the value of Monaco Editor


So i am trying to build a web based editor using Monaco, and I would like to save the code that I wrote in the editor in like a file by clicking a button and keep it even if I restart the server How can I do that ?

const value = ``;
const editor = monaco.editor.create(app, {
  model: monaco.editor.createModel(
      value,
      "domain",
      monaco.Uri.parse("file:///main.dm")
  ),

When I start the server, the editor is empty because value=''


Solution

  • Browser based apps have no direct access to the file system. So you only have 2 options:

    1. Provide a download for the user on button click. The browser will then save the provided text in a file in its download folder.
    2. Send the text to a server (if you have one, of course), which then has to store the text somewhere and provide it later on.

    For option one the approach is usually like this:

    /**
     * Stores the the text in a local file. Usually the web browser determines where the file is stored (download folder).
     *
     * @param text The content of the file.
     * @param fileName The name of the target file (should not contain a path).
     */
    export const saveTextAsFile = (text: string, fileName: string): void => {
        const blob = new Blob([text], { type: "text/plain" });
        const downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        downloadLink.innerHTML = "Download File";
        if (window.webkitURL) {
            // No need to add the download element to the DOM in Webkit.
            downloadLink.href = window.webkitURL.createObjectURL(blob);
        } else {
            downloadLink.href = window.URL.createObjectURL(blob);
            downloadLink.onclick = (event: MouseEvent): void => {
                if (event.target) {
                    document.body.removeChild(event.target as Node);
                }
            };
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
    
        downloadLink.click();
    
        if (window.webkitURL) {
            window.webkitURL.revokeObjectURL(downloadLink.href);
        } else {
            window.URL.revokeObjectURL(downloadLink.href);
        }
    };