Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to read text file in folder with javascript

I have a folder structure like this

index.html
file.txt

in the index.html I have a script that wants to read the file.txt and assign it to a variable, say x.

async function loadFile(file) {
    let text = await file.text();
    console.log(text);
    return text
}

var x = loadFile("file.txt")

but this returns an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

main.js:35 
        
       Uncaught (in promise) TypeError: file.text is not a function
    at loadFile (main.js:35:27)
    at main.js:39:13

what to do? I just want to assign file.txt content to a variable.

>Solution :

JavaScript in browser doesn’t give you direct access to file system.
What you did is just pass a string to your function and call text() on it. Sadly it doesn’t work like that.

Here are two workarounds I know of:

1. fetch api

If you have an http server serving your files then you make a request using fetch() to obtain its content in JS. Read the docs here :

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Note that it won’t work on pages loaded with file:// URI scheme. You need http(s). If you have python installed run python -m http.server 8000 in directory containing files to be served.

2. FileReader

If the file is to be selected by user as input to a form then you can use FileReader

Have a look these links:
webdev has great explaination for this

https://web.dev/read-files/

also see the docs

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading