skip to Main Content

I want to convert a txt file, which i have uploaded in a form, into string in javascript.

text in my text file is "my name is x".
Now i want to store the text of the file in javascript as string.
Is there any basic function? looking for a easy solution
**note: do not want to use node.js

3

Answers


  1. async function readFile(file) {
        const text = await file.text();
        console.log(text); // Will output: "my name is x"
        return text;
    }
    
    // Usage
    fileInput.addEventListener('change', async (e) => {
        const text = await readFile(e.target.files[0]);
        // Use your text here
    });
    
    Login or Signup to reply.
  2. Yes, you can easily achieve this using the FileReader API in JavaScript. Here’s a simple example to read the contents of a .txt file and store it as a string:
    HTML and JavaScript Code

    <!DOCTYPE html>
    <html>
    <head>
        <title>Read Text File</title>
    </head>
    <body>
        <h1>Upload a Text File</h1>
        <input type="file" id="fileInput" accept=".txt" />
        <p id="fileContent"></p>
    
        <script>
            document.getElementById("fileInput").addEventListener("change", function(event) {
                const file = event.target.files[0]; // Get the uploaded file
                if (file) {
                    const reader = new FileReader(); // Create a FileReader object
                    
                    reader.onload = function(e) {
                        const fileContent = e.target.result; // Get the file content as a string
                        console.log(fileContent); // Output the content to console
                        document.getElementById("fileContent").innerText = fileContent; // Display content
                    };
    
                    reader.readAsText(file); // Read the file as a text
                } else {
                    alert("No file selected.");
                }
            });
        </script>
    </body>
    </html>
    Login or Signup to reply.
  3. const fs = require('fs');
      fs.readFile('Input.txt', (err, data) => {
      const result = data.toString();
      console.log(result);
    });
    

    Simplest way!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search