【问题标题】:How can I save the value of Monaco Editor如何保存摩纳哥编辑器的价值
【发布时间】:2022-01-26 01:15:21
【问题描述】:

所以我正在尝试使用 Monaco 构建一个基于 Web 的编辑器,我想通过单击一个按钮将我在编辑器中编写的代码保存为一个文件,即使我重新启动服务器也可以保留它 我该怎么做?

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

当我启动服务器时,编辑器是空的,因为 value=''

【问题讨论】:

    标签: typescript monaco-editor language-server-protocol


    【解决方案1】:

    基于浏览器的应用程序无法直接访问文件系统。所以你只有两个选择:

    1. 在按钮单击时为用户提供下载。然后,浏览器会将提供的文本保存在其下载文件夹中的文件中。
    2. 将文本发送到服务器(当然,如果您有的话),然后服务器必须将文本存储在某处并稍后提供。

    对于选项一,方法通常是这样的:

    /**
     * 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);
        }
    };
    
    

    【讨论】:

    • 感谢您的回复,我有几个问题。如果我想将文本保存在文件中而不是每次都下载新文件,我该怎么办?以及如何加载文件内容?
    • 每个 SO 问题都应该关注一个问题(问答风格)。如果您有更多问题,请为每个问题写一个 SO 问题。
    【解决方案2】:

    所以要加载我使用的文件

    function loadFileAsText()
    {
      var fileToLoad = (<HTMLInputElement>document.getElementById("fileToLoad")).files![0];
    
      var fileReader = new FileReader();
      fileReader.onload = function(fileLoadedEvent)
      {
        var textFromFileLoaded = fileLoadedEvent.target!.result;
        //Do whatever we want with textFromFileLoaded
        editor.setValue(textFromFileLoaded!.toString());
      };
      fileReader.readAsText(fileToLoad, "UTF-8");
    }
    

    显然,由于安全问题,我们无法将内容保存在现有文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-21
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2023-04-04
      相关资源
      最近更新 更多