Home > Net >  Modern way of accessing-reading-parsing a file with JavaScript
Modern way of accessing-reading-parsing a file with JavaScript

Time:10-05

Reading answers on this topic, I got confused. (Lots of answers, each one saying the others are outdated, etc.)

Suppose I have words.txt file in the same directory as my index.html and script.js. The contents of the text file are comma separated words: "apple", "hello", ...

What is the modern way of browser-side local-page accessing/reading/parsing that text file?

CodePudding user response:

Javascript runs in the browser on the client machine, and it cannot access the underlying file system. If I understood you correctly, you want to read and parse a file into some kind of an array.
That's done on the server. On the server, there exists a file called words.txt, and you can make an API endpoint that will return the contents of a file.

However, you can make another .js for example words.js that will have an array of strings called words. When loading scripts in html load words.js before myfile.js (myfile.js is your javascript), and you will be able to access words from myfile.js.

Example of how it's done:

index.html

<!DOCTYPE html>
<html>
  <head>...</head>
  <body>
    ...
    <script src="words.js"></script> <!-- Loading words here -->
    <script src="myfile.js"></script> <!-- Loading your script here -->
  </body>
</html>

words.js

const words = ["apple", "hello",...];

myfile.js

words.forEach((word) => {/* Do something */});

A project like this becomes very complicated very fast because you need to load javascript files in the right order. Because of this bundlers exist, like webpack that will bundle your code and you won't have to worry about this stuff.

CodePudding user response:

fetch() in combination with d3.js is pretty good at deciphering any csv file:

fetch("https://date.nager.at/PublicHoliday/Country/DE/2022/CSV")
.then(r=>r.text()).then(csv=>console.log(d3.csvParse(csv)));
<script src="https://d3js.org/d3.v7.min.js"></script>

Once the CSV has been parsed you can of course also list the values without the keys:

fetch("https://date.nager.at/PublicHoliday/Country/DE/2022/CSV")
.then(r=>r.text()).then(csv=>console.log(d3.csvParse(csv).map(o=>Object.values(o))));
<script src="https://d3js.org/d3.v7.min.js"></script>

  • Related