代表者の戯言

Download texxtfile



Let’s create a text file using JavaScript.


The following program was created to allow the user to specify the file name, file content, and the destination folder.


Please feel free to use it as a reference.


******************************************************************************************************

<!DOCTYPE html>

<html lang="ja">

<head>

<meta charset="UTF-8">

<title>save textfile</title>

</head>

<body>

<p>filename: <input id="text1" size="30"></p>

<p>content:<br>

<textarea id="text2" rows="5" cols="40" placeholder="insert words here"

></textarea>

</p>

<button onclick="saveFile()">select folder and save</button>

<script>

async function saveFile() {

const fileName = document.getElementById("text1").value.trim() || "untitled";

const content = document.getElementById("text2").value;

try {

const options = {

suggestedName: fileName + ".txt",

types: [{

description: 'Text Files',

accept: { 'text/plain': ['.txt'] }

}]

};

// save file dialog

const handle = await window.showSaveFilePicker(options);

// make stream

const writable = await handle.createWritable();

await writable.write(content);

await writable.close();

alert("saved!: " + handle.name);

} catch (err) {

if (err.name !== 'AbortError') {

console.error("error:", err);

alert("you could not save it");

} else {

console.log("save canceled");

}

}

}

</script>

</body>

</html>

******************************************************************************************************
screen