-3

i have file in local server (this same directory). I will have 1000 numbers in file

data.txt

123
456
677

I'd like to load this data into the table using JS and create a table

let table = [123, 456, 677]
  • 1
    It depends on where your javascript runs, if on backend - one approach, if in browser - another – qiAlex Feb 04 '20 at 09:39
  • Does this answer your question? [How to read a local text file?](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file) – qiAlex Feb 04 '20 at 09:40

1 Answers1

1

I'm going to assume that you want to do this on a browser.

To do it, you'd read the file as text via ajax, then parse it into an array by splitting on line breaks, then parse the lines as numbers via parseInt or similar.

For example:

fetch("data.txt")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text();
})
.then(text => {
    table = text.split(/[\r\n]+/)            // Split into lines
                .filter(line => line.trim()) // Remove blank lines
                .map(str => parseInt(str));  // Parse lines to numbers
    // Use table here...
})
.catch(error => {
    // ...handle/report error here
});

parseInt isn't your only option for parsing the strings, see my answer here for a list of your various options and their pros and cons.

More to explore:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875