Home > Enterprise >  How to make JS read the contents of a local text file
How to make JS read the contents of a local text file

Time:02-27

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?

CodePudding user response:

If you're using node.js you can use the File system api

const fs = require("fs");
let contents = fs.readFileSync("code.txt").toString().split(/\r?\n/);
console.log(contents);

CodePudding user response:

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" ]

CodePudding user response:

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

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