I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input>
tags or user interaction whatsoever.
On my research, I found two tutorials that are heavily cited in SO:
However, there is a problem. Both of this tutorials require user interaction via the input
tag, which is a life killer since I want to read the contents of the file automatically into a string.
So far I managed to get the following code:
let readFile = function(path) {
let reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
console.log(text);
};
// Read in the image file as a data URL.
reader.readAsText(MissingFileHandle);
};
But as you can see, I am missing an important step, I am missing MissingFileHandle
. My idea would be to pass a path
to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.
Given a relative path, how can I read the contents of a file using HTML 5 without using <input>
tags?
HTML 5 provides a standard way to interact with local files with the help of File API. The File API allows interaction with single, multiple as well as BLOB files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.
Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.
Web browsers (and JavaScript) can only access local files with user permission. To standardize the file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Is it possible to load a file with JS/HTML5 FileReader on non served page?
How to open a local disk file with Javascript?
How to set a value to a file input in HTML?
Javascript read file without using input
These links help you to find answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With