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
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.
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
So I am trying to learn Javascript. I created a JSON file called "Ancest.json". Then, in a new file on netbeans I tried to execute this code accessing that file:
var ancestry = JSON.parse(Ancest);
console.log(ancestry.length);
I am getting a rejection saying "Ancest is not defined".
What am I doing wrong? Attached is a screen shot. Thank you for your time.
JSON.parse method accepts a string which is the JSON object to be parsed into a JavaScript object.
You need to get the content of the file or to move the content of your JSON file into a string variable in the js file. Then you can parse it:
console.log(JSON.parse('{ "a": "test" }'));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
You need to assign a string Ancest or var Ancest = './Ancest.json'; Depending on the location and path of Ancest.json, you may have to put in the full path or linked path if the .js file exists in the same path. Also put the path in single quote or double quote. Make sure you have access to read the file.
It also needs correct file system permissions. This is all contingent on who this js is running as, delegate permissions on the parent directories, etc, etc. Chances are permissions are okay for read.
I could not find out why this part of my code doesn't work:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file);
alert (FileText);
The intention is, I think, clear: FilePath contains the filename of a file (passed via parameter FileName) containing logging data (a plain ASCII text file, with one line per log entry), the file is located in the same directory as the web page is (loc), and I want to embed the text into my html document somewhere further down the code.
Since the logged lines are of different kinds (e.g. errors, warning, other blabla ...) each line needs to be parsed and processed.
I intended to split FileText into an array, and loop through it. I cannot, however, get readastext to work. Though, according to FireFox debugger, FilePath does contain the correct string, I get the NS_ERROR_FAILURE, which I, according to the sparse documentation I found about it, must consider to be the 'zillionst stupid way to say "File not found".
I found tons of other posts from people messing with the file API, and tons of snippets taken from the mozilla docs which don't help me out. I read that there are maybe other ways to read a file, e.g. through Ajax, JQuery ... but before I go that way ... is it really, really absolutely impossible to accomplish what I want using just plain JavaScript, and if it is possible, who can provide a code snippet?
Thanks very much,
Armin.
You have quotes around "FilePath":
var file = new File("FilePath");
This means it's going to try to load a file with the path "FilePath".
Pretty sure this is what you want:
var file = new File(FilePath);
On the other hand, Quentin is absolutely right. You're not going to be able to access local files if this code is running in a web page.
Since you are using window.location.pathname i assume that you are in a browser and want to use that code to "navigate" to files on the server based on the URL path.
I think your whole approach is wrong, and it would be a security issue to have something like that possible.
The File API can be used strictly on files selected by the user, and not on any file. The MDN description is self-explanatory:
Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.
Yes, you can specify a path to any file in the File constructor method, but that doesn't mean you can access any file. Another excerpt from MDN:
This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.
This code did the trick:
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();
and, in addition, an objXMLhttp.onreadystatechange=function() ... event handler must be implemented, which is the code acutally receiving the data, like so:
objXMLhttp.onreadystatechange=function()
{
if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
{
var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
....
}
}
Easy win is to do an ajax request for the path...you should have your page that contains the js and files served by a web server. Any other way needs other priveleges and if you were to get files from a users computer without an uploader or anything like that would be a security breach
I am working on a window application where I have to look for all pdf files, parse them and search a keyword occurrence in them with the help of javascript. I tried using pdf.js but found no solution for local files. It shows me following error;
XMLHttpRequest cannot load file:///Hello.pdf. Cross origin requests are only supported for HTTP. (sample file name is Hello.pdf)
The PDFJS.getDocument method accepts either a URL to a file, or an ArrayBuffer of the PDF file. So what you can do, is read the file into an ArrayBuffer (perhaps using FileReader.readAsArrayBuffer), and then pass the buffer to getDocument.
See here.
If you want to run it locally and it has to be JavaScript I would look for Node.js modules that can handle PDF's, like pdf2json.
I have to read a file from the file system of my phone. Essentially its to check if the file contains a word. The file is located in the /sys folder of my phone. I know I can get the contents of the File using FileReader.readAsText(file) to get the contents as a string and then parse it for the word. But how do I make the "file" object to pass to the FileReader object. Thanks in advance!
Edit: Just wanted to add here:
Can I use the File constructor here?
var file = File("/path/to/file");
You can only read data from your app folder (via XMLHttpRequest) and from the SD Card. You cannot read data from any other place in a Firefox OS app.