-2

../chart.txt

[ 0, 1, 2, 3 ]

myJs.js

var chart = []
chart = //chart.txt file data

.

readFile( Path, Options, Callback)

how to insert txt file data in javascript.

  • 2
    Well, those are some fragments of code which could be involved in doing what you want. It isn't clear how they are connected or what *specific* problem you are having. You should read [ask] – Quentin Nov 30 '21 at 10:42
  • This link will give you idea https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/ – glovemobile Nov 30 '21 at 10:46
  • @glovemobile — Nothing in the question suggests they are dealing with code in the browser (if they were, then there are plenty of good duplicate links on Stackoverflow itself). – Quentin Nov 30 '21 at 10:48
  • Since your tag is javascript, here it is: https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file – glovemobile Nov 30 '21 at 11:04
  • @glovemobile — That's assuming its a text file local to the user and not a text file local to the website. This question needs a lot of work. – Quentin Nov 30 '21 at 11:05
  • Agree with you @Quentin. – glovemobile Nov 30 '21 at 11:07
  • if i use this way can i problem solve. http://127.0.0.1:5550/myJs.js – uils tumur Nov 30 '21 at 11:23

1 Answers1

-1

I'm posting code in nodejs modules since you're accessing a local filesystem file

chart.txt

0,1,2,3,4

myJs.js

const fs = require('fs');

let chart = [];
chart = fs.readFileSync('file_path').toString().split(',');

If you don't want to change the format of your txt:

const fs = require('fs');

let chart = [];
chart = fs.readFileSync('file_path').toString().replace(/\[|\]| +/g, '').split(',');

Shorter:

const fs = require('fs');

let chart = null;
try {
    chart = JSON.parse(fs.readFileSync('file_path').toString());
} catch(_e) { chart = []; }
Nick
  • 593
  • 12
  • "I'm posting code in nodejs" — They didn't say they were using Node.js (and there are plenty of duplicates if they are). – Quentin Nov 30 '21 at 10:51
  • `split(',');` — The data is in JSON format. That's a terrible way to deal with it. – Quentin Nov 30 '21 at 10:52
  • 1
    @Quentin I guessed he's using nodejs since he's accessing filesystem files. He haven't said what he's using so this will work in that case. Accurate answers come from accurate questions. – Nick Nov 30 '21 at 10:54
  • `split(',')` will give you the desired solution if you don't care of the content of the array, if you just want numbers you can `map`() the content – Nick Nov 30 '21 at 10:55
  • i try it. error => myJs.js:1 Uncaught ReferenceError: require is not defined at myJs.js:1 – uils tumur Nov 30 '21 at 10:56
  • 1
    @uilstumur Dude are you using nodejs or browser?? Can you please specify? – Nick Nov 30 '21 at 10:57
  • i using browser – uils tumur Nov 30 '21 at 11:00
  • You need an input[type="file"] – Nick Nov 30 '21 at 11:04