'How to make JS read the contents of a local text file

I know using JS to read the contents of a .txt is possible.

For example, I have a text file code.txt which contains

Abc
Ghi
123466
bored
idk

And I have index.js. I would like to use the contents of code.txt to create an array into index.js.

So, in that example, I would like an array like this to appear in index.js.

const entcode = [
  "Abc",
  "Ghi",
  "123466",
  "bored",
  "idk",
];

Is there a way to do that?



Solution 1:[1]

Yes!

  1. Install Deno (a JavaScript/TypeScript runtime that works outside your browser)

  2. Read the file and create the array like this:

./index.js:

const text = (await Deno.readTextFile('./code.txt')).trim();
const entcode = text.split(/\r?\n/);
console.log(entcode);
  1. Run it:
$ deno run index.js
??  ?Deno requests read access to "./code.txt". Run again with --allow-read to bypass this prompt.
   Allow? [y/n (y = yes allow, n = no deny)]  y
[ "Abc", "Ghi", "123466", "bored", "idk" ]

Solution 2:[2]

If you use jQuery you can get the data by the below code.

jQuery.get('http://localhost/code.txt', (data) => {
    const res = data;
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsejcksn
Solution 2 Zahid Hasan