Read a text file using Javascript.

この記事は約6分で読めます。
スポンサーリンク

Things I want to do

This code reads a locally stored text file using Javascript.

For instructions on loading via drag and drop, please see below.

スポンサーリンク

Reading via File System API

By clicking the ‘Load Text’ button displayed in the following HTML, you can select and load a file from the file selector.

The loaded data is stored in the text field.

<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8" />
    <title>text読込</title>
</head>
<body>
    <input type=button id="load" value="text読込">

    <script>
        async function loadText() {
            const opt = {
                types: [ 
                    {
                        accept: { "text/plain": [".txt"] }
                    }
                ]
            };
            const handle = await window.showOpenFilePicker(opt);
            if (handle[0] != undefined) {
                const file = await handle[0].getFile();
                const text = await file.text();
                console.log(text);
            }
        }
        document.getElementById("load").onclick = loadText;
    </script>

</body>
</html>

The following Opt options are for reading files. In this example, since we are targeting a text file, it is ‘text/plain’:[‘.txt’]This setting is being configured. For common MIME types, please refer to the following page.

Common media types - HTTP | MDN
This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.
            const opt = {
                types: [ 
                    {
                        accept: { "text/plain": [".txt"] }
                    }
                ]
            };

The following line displays the file selector.

`showOpenFilePicker` must be called immediately after a user operation such as a click. For example, if you perform a heavy process after a click but before calling `showOpenFilePicker`, or if you stop the process for debugging, an error like the following will be displayed and the process will fail. (You cannot directly call `showOpenFilePicker` or `loadText` without a click or other user interaction.)

Uncaught (in promise) DOMException: Failed to execute showOpenFilePicker on Window: Must be handling a user gesture to show a file picker.
at HTMLInputElement.loadText

const handle = await window.showOpenFilePicker(opt);

The following code reads the contents of a file. The file contents are saved to the `text` variable as a String.

In this example, only one file can be selected, but `handle` is an array.

In this example, the file content is fixed as text, so we read it using `file.text()`. Binary files are read using `file.arrayBuffer()`.

            const handle = await window.showOpenFilePicker(opt);
            if (handle[0] != undefined) {
                const file = await handle[0].getFile();
                const text = await file.text();
                console.log(text);
            }
スポンサーリンク

Result

I was able to read a locally saved text file using a file selector.

コメント

タイトルとURLをコピーしました