typescript - ฉันจะบันทึกค่าของ Monaco Editor ได้อย่างไร
ดังนั้นฉันกำลังพยายามสร้างตัวแก้ไขบนเว็บโดยใช้ Monaco และฉันต้องการบันทึกโค้ดที่ฉันเขียนในตัวแก้ไขเป็นไฟล์โดยการคลิกปุ่ม และเก็บมันไว้แม้ว่าฉันจะรีสตาร์ทเซิร์ฟเวอร์ ฉันจะทำได้อย่างไร?
const value = ``;
const editor = monaco.editor.create(app, {
model: monaco.editor.createModel(
value,
"domain",
monaco.Uri.parse("file:///main.dm")
),
เมื่อฉันเริ่มเซิร์ฟเวอร์ ตัวแก้ไขจะแสดงว่างเพราะค่า=''
คำตอบ #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);
}
};
คำตอบ #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");
}
และดูเหมือนว่าเราไม่สามารถบันทึกเนื้อหาในไฟล์ที่มีอยู่เนื่องจากปัญหาด้านความปลอดภัย
