User Tools

Site Tools


java-script:read-file

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:read-file [2023/08/04 23:20] odeftajava-script:read-file [2023/08/20 01:19] (current) – ↷ Links adapted because of a move operation 217.113.194.57
Line 3: Line 3:
 ===== Read a file in web browser ===== ===== Read a file in web browser =====
  
-The following script reads the content of a file selected by the user and then displays those contents in a <pre> element. \\ When the "Read File" button is clicked, the readFile function is called, which reads the file selected in the file input field and writes its contents to the fileContents element.+The following script reads the content of a file selected by the user and then displays those contents in a **<pre>** element. \\ When the "Read File" button is clicked, the **readFile** function is called, which reads the file selected in the file input field and writes its contents to the **fileContents** element.
  
 <note> <note>
Line 25: Line 25:
  
 </note> </note>
 +
 +==== Using callback function (on onload event) ====
 +
 +The **FileReader** object's **onload** event uses a callback function to handle the event when the file's content is fully loaded into memory. 
 +
 +<code javascript read-file-web-callback.html>
 +<!DOCTYPE html>
 +<html>
 +<head>
 +    <title>File Reader Example</title>
 +    <script>
 +        function readFile() {
 +            const fileInput = document.getElementById('myFile');
 +            const file = fileInput.files[0];
 +            const reader = new FileReader();
 +
 +            reader.onload = function(e) {
 +                const contents = e.target.result;
 +                document.getElementById('fileContents').innerText = contents;
 +            };
 +
 +            reader.readAsText(file);
 +        }
 +    </script>
 +</head>
 +<body>
 +    <input type="file" id="myFile">
 +    <button onclick="readFile()">Read File</button>
 +    <pre id="fileContents"></pre>
 +</body>
 +</html>
 +</code>
 +
 +==== Using Promise ====
 +
 +If you prefer using **Promise** instead of the **onload** event, you can create a wrapper function around the FileReader API that returns a promise. \\ 
 +A new function **readAsText** wraps the FileReader API and returns a promise. This promise resolves with the file's contents when the onload event is fired, and rejects if there's an error during the read operation (onerror). \\ Now the readFile function uses this readAsText function and handles the file content in a then clause, which gives a more modern, promise-based way of handling the file reading operation.
 +
 +<code javascript read-file-web-promise.html>
 +<!DOCTYPE html>
 +<html>
 +<head>
 +    <title>File Reader Example</title>
 +    <script>
 +        function readFile() {
 +            const fileInput = document.getElementById('myFile');
 +            const file = fileInput.files[0];
 +
 +            readAsText(file).then(contents => {
 +                document.getElementById('fileContents').innerText = contents;
 +            });
 +        }
 +
 +        function readAsText(file) {
 +            return new Promise((resolve, reject) => {
 +                const reader = new FileReader();
 +
 +                reader.onload = function(e) {
 +                    resolve(e.target.result);
 +                };
 +                
 +                reader.onerror = function(e) {
 +                    reject(e);
 +                };
 +
 +                reader.readAsText(file);
 +            });
 +        }
 +    </script>
 +</head>
 +<body>
 +    <input type="file" id="myFile">
 +    <button onclick="readFile()">Read File</button>
 +    <pre id="fileContents"></pre>
 +</body>
 +</html>
 +</code>
 +
 +===== Read a file in Node.js =====
 +
 +First you should [[java-script:node-js:setup|initialize the directory as a node.js es6+ module.]]
 +
 +<code javascript fileReader.js>
 +import fs from 'fs/promises';
 +
 +export async function readFile(filePath) {
 +    try {
 +        const data = await fs.readFile(filePath, 'utf8');
 +        console.log('File content:', data);
 +    } catch (err) {
 +        console.error('An error occurred:', err);
 +    }
 +}
 +</code>
 +
 +<code javascript index.js>
 +import { readFile } from './fileReader.js';
 +
 +const fileName = process.argv[2];
 +if (!fileName) {
 +    console.log('Please provide a file name as a command-line argument');
 +    process.exit(1);
 +}
 +
 +readFile(fileName);
 +</code>
 +
 +To run it:
 +<code>
 +node ./index.js C:/test.txt
 +</code>
  
  
  
  
java-script/read-file.1691180440.txt.gz · Last modified: 2023/08/04 23:20 by odefta