how to read text file in folder with javascript - 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
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

Related

How to read a local server JSON file with react?

I need to read a JSON file located on my machine with my react application and nothing seem to work.
I tried importing fs (with import and require) but it returns a blank object and I cannot use any of it's functions.
Jquery doesn't seem to find my file either.
Everywhere I searched they use FS, Jquery or FileReader (the last one is always used for files that the client uploaded to the page).
This is one of the solutions I tried with FS:
const fs = require("fs");
export default function getJson() {
let rawdata = fs.readFile("file.json");
let json = JSON.parse(rawdata);
console.log(json);
}
When I reload the browser
TypeError: fs.readFile is not a function
With Jquery I tried this:
import $ from "jquery";
export default function getJson() {
$.getJSON("file.json", function() {
console.log("success");
});
}
The console shows this:
Failed to load resource: the server responded with a status of 404 (Not Found)
I hope you can help me.
Thanks in advance!
fs is an inrospection that connects Node's engine to the underlying OS. It does not exist in browser code (e.g. ReactJS).
For security measures, browsers deny JS from interacting with the underlying platform. So to read the file, you have two option (as far as I know):
Either create a file-input field in html (like the file-upload fields you usually see). Or you need to serve the file by some server. You can put the file in your assets folder, and then request it in react.
Update 1:
From my experience, one of the easier ways to include a "runtime-configuration" is to serve the configuration as an asset.
I don't have much experience in ReactJS, but the idea is the same.
Let's say you put the config.json in Public/json/config.json. Then you can read this file from the application by requesting it.
here's an example:
fetch("/json/config.json").then(resp=>resp.json()).then(console.log);
and here's a small working stackblitz example

How to get the url serving the current js file

Suppose I have a site at www.somewhere.com that loads a javascript file called Test.js hosted at www.aplace.com. From within Test.js, how can I get the url www.aplace.com?
When I use window.location, I get the url of the site (somewhere.com) instead of the url of Test.js.
The reason I am asking is because I need to make a post request from Test.js to www.aplace.com/dirA/dirB/dirC/Test.js to www.aplace.com/dirD but I can't hardcode the URL.
They should be in <script> in src='{THE_URL}', perhaps try scraping if API is not present.

PHP to Javascript: dirname and document_root

I got a little problem. I am working on a project and I got my root, then I got 2 folders: website1 and website2.
website1 is the staff panel, where the upload script is on (where this problem is on). website2 is the website the 'customer' will see. Here all the uploaded images, PDFs etc. are uploaded to.
So, I have a few notes before I start:
I cannot use PHP in my Javascript. The Javascript is in .js files and not in my .php file.
I cannot do this at my AJAX request as something client-side has to be done correctly to see the image.
So basically, I am in website1 and when I upload a file (with DropzoneJS (http://www.dropzonejs.com/)) it does a AJAX request. Here it has to upload a file to a directory in website2. In website1 I have to see that image after uploading it in a IMG tag.
So in PHP I got this:
$uploadPath = filter_input(INPUT_POST, 'uploadPath');
$uploadPath = dirname(getenv('DOCUMENT_ROOT')) . '/' . $uploadPath;
This works and the file gets uploaded to that directory. $uploadPath is this (in Javascript, sent as POST parameter in AJAX request):
/SITE2/assets/uploads/
Now I need to translate the dirname and getenv('DOCUMENT_ROOT') into Javascript. I tried document.location.hostname but this does return a different value than getenv('DOCUMENT_ROOT').
document.location.hostname: 127.0.0.1
getenv('DOCUMENT_ROOT'): D:/xampp/htdocs
How can I get the same value as getenv('DOCUMENT_ROOT') in Javascript?
In php file you can create script with JavaScript variable like this:
<script>
var DOCUMENT_ROOT = "<?= getenv('DOCUMENT_ROOT') ?>";
</script>
the other option is to have your JavaScript file as PHP script then you can use PHP code inside.
You have two options, but I caution you sending the actual file path on the server/disk to the client side is a bad idea.
Use Ajax so the client sends a request like $.ajax({url: "getdir.php", success: someJSFuntion } );
Change your JavaScript file to be a ".php" file and then include the code right in there.
There is no spec that says you can't have your JS file be a ".php" file. So you'd link to it like this:
<script type="text/javascript" src="/js/myjs.php"></script>
And that would let you use PHP directly in your JS file.
Check out php.js for a JavaScript port of dirname...
http://phpjs.org/functions/dirname/
As for getenv('DOCUMENT_ROOT'), you can't get this variable value via JavaScript. The reason for this is the client-side "location" of the JavaScript file says nothing about it's actual location on the server. The best you can do is get the parent directory of the file or the domain name.
For example:
http://example.com/path/to/file
The "DOCUMENT_ROOT" as far as JavaScript is concerned is...
/path/to
It seems very improper to even assume the need to have the server-side location of the file available to the JavaScript. I would simply use either a specific URL query that indicates what location to use, or to send the location back with the AJAX response since you can add whatever you need there.
{
"document-root": "/SITE2/assets/uploads/",
"normal-response": {
...
}
}
And then wherever you would normally use what is normally received, this use...
// For example
var response = JSON.parse (request.responseText);
// Normal response
console.log (response['normal-response'][...]);
// Document Root
console.log (response['document-root']);

how to parse a local copy of pdf files and search keyword occurrence using javascript?

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.

JavaScript googlemaps read coordinates from file

I want to display some markers using googlemaps. The information (coordinates) are stored in a local *.csv file (wich I want to use a "ressource-file").
How can I read this *.csv file? If I use "jQuery.get('myFile.csv', function (data) {..." it dosn't work.
The error message is: Cross origin requests are only supported for protocol schemes
Do I hava to make a file selection to read the file? Is there no other way?
Thanks
Is it possible that you are trying to load data from a file and not a running server(for example by double-clicking the .html from your file manager)?
If your are on the file:// protocol (which you can see in your url) this will not work. You could try changing to the development directory and runnig python3 -m http.server which will start a small development server. You can than change to http://localhost:8000 and see if it works.

Categories

Resources