Java How can I read a local file into an array in JavaScript?

  • Thread starter Thread starter Trying2Learn
  • Start date Start date
  • Tags Tags
    Array Javascript
AI Thread Summary
JavaScript cannot directly read local files due to browser security restrictions, which prevent unauthorized access to a user's file system. To read a local file, users must utilize the File API with an input element that allows file selection. The recommended approach involves creating an HTML file input element and an associated JavaScript function to handle file loading. The JavaScript function reads the file's content asynchronously, splits the text into an array based on line breaks, and converts the string values into numbers. Example code demonstrates how to achieve this, including how to sum the numbers in the array. This method is essential for applications like ThreeJS that require local file data while adhering to browser security protocols.
Trying2Learn
Messages
375
Reaction score
57
TL;DR Summary
reading a file
Hello

I am aware that it is not natural for JavaScript to read a file; however I see it is being done. I am trying to read a local file of 100 numbers (separated by line breaks) into an array in JavaScript

(I am aware that there are better ways to do this, but this is going to be the way I need (it has to do with ThreeJS and all runs are local files -- please understand that.)

All the examples have such power: buttons to select file names, etc. I do not need any of that. I just need something like this (allow me to make it up using C pointers)

var vector[]
var fp = openFile("./name.txt")
for( i = 0; i < 100; i++) read(fp, "%f", (vector + i))


Then, later, I can do things with that vector
The file will have only 100 numbers in the list.
The file will always have the same name.
It will exist for reading.
I am not interested in efficiency or power, or multiple files.
I do not care about closing the file, unless it is easy.Just the above. I just need to read 100 numbers from an input file.
3.14159
2.6
100.
-10.
3.4
.
.
.
etc.

What should I put in the html file
What should I put in the associated js file

Please direct me...
 
Technology news on Phys.org
jedishrfu said:
When running javascript inside a browser, you are limited in what files you can access. Browsers try to sandbox your application and restrict access to local files on the user's machine.

Here's a recipe for reading files located in the same directory on the web server as the javascript program.

https://www.geeksforgeeks.org/javascript-program-to-read-text-file/

I have seen that before, but I cannot get it to work for me...

I cannot seem to actually read in the numbers.

The input data file is simple:
100.0
-10.3
3.14159
and so one... 100 lines

In your example, I do not see the array, the indexing, etc.
 
I assume you are talking about JavaScript running in a browser (rather than in Node JS or an Electron app)? Unfortunately @jedishrfu's link will not work in a browser.

Code running in a browser cannot access files on your computer directly - if it could then any website you visited could read though all your files looking for bank details, passwords etc.

The only way you can access local files from a browser is by using the file chooser dialog and the File API something like the code below (note that the forum software objects to the word 'onchange' in a code block: you need to use this in place of '[blocked]' below).

HTML:
<input id="fileInput" type="file" [blocked]="loadFile(this.files[0])">

JavaScript:
async function loadFile(file) {
  // Show the file details.
  document.querySelector('#description').innerText =
    'File name: ' + file.name + '\n' +
    'Size: ' + file.size + ' bytes\n' +
    'Modified: ' + new Date(file.lastModified).toISOString() + '\n' +
    'MIME type: ' + file.type;

  // Asynchronously load the file contents.
  const textContent = await file.text();
  document.querySelector('#contents').innerText = textContent;
}
You can see this in action in this CodePen https://codepen.io/pbuk/pen/yLVjaRO.
 
Last edited:
Assuming you got the textContent of your file (similar to what is proposed in post #4), you can create the array like so, by splitting the string on line breaks:
JavaScript:
var
    textContent = `3.14159
2.6
100.
-10.
3.4`,
    arrayString = textContent.split(/\n/),
    arrayNumber = [...arrayString]; // copy array

// convert String to Number 
arrayNumber.forEach(function(string, key, array){
    array[key] = Number(string);
});

// test function
function sum(array){
    var sum = 0;
    
    array.forEach(function(number){
        sum += number;
    });

    return sum;
}

// results
console.log(arrayString, sum(arrayString), arrayNumber, sum(arrayNumber));

Results in console should be:
Code:
Array(5) [ "3.14159", "2.6", "100.", "-10.", "3.4" ]
03.141592.6100.-10.3.4 
Array(5) [ 3.14159, 2.6, 100, -10, 3.4 ]
99.14159000000001

Note that the array will be filled with strings, not numbers. To convert a string to a number, you can use the Number object.
 
  • Like
Likes Trying2Learn
More succinctly coded in modern javascript as:
JavaScript:
var
    textContent = `3.14159
2.6
100.
-10.
3.4`,
    arrayString = textContent.split(/\n/),
    arrayNumber = arrayString.map((string) => parseFloat(string));
});

// test function
function sum(array) {
  return array.reduce((sum, element) => (sum + element), 0);
}

// results
console.log(arrayString, sum(arrayString), arrayNumber, sum(arrayNumber));
 
  • Like
Likes Trying2Learn
Thank you, everyone!
 

Similar threads

Replies
4
Views
1K
Replies
8
Views
2K
Replies
21
Views
6K
Replies
3
Views
2K
Replies
33
Views
5K
Replies
8
Views
6K
Replies
5
Views
2K
Back
Top