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

  • Context: Java 
  • Thread starter Thread starter Trying2Learn
  • Start date Start date
  • Tags Tags
    Array Javascript
Click For Summary

Discussion Overview

The discussion revolves around reading a local file containing 100 numbers into an array using JavaScript. Participants explore the limitations of accessing local files in a browser environment and propose various methods to achieve the desired outcome, focusing on both theoretical and practical aspects.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Exploratory

Main Points Raised

  • One participant expresses a need to read a local file directly into an array without using file selection dialogs, citing a specific use case with ThreeJS.
  • Several participants clarify that JavaScript running in a browser cannot directly access local files due to security restrictions, emphasizing the sandboxing of browser applications.
  • One participant provides a code snippet using the File API and a file input element to read file contents asynchronously, highlighting the necessity of user interaction for file access.
  • Another participant suggests a method to convert the text content of the file into an array by splitting the string on line breaks and converting the resulting strings to numbers.
  • Further contributions refine the array creation process, proposing more succinct modern JavaScript syntax for converting strings to numbers and summing the array elements.

Areas of Agreement / Disagreement

Participants generally agree on the limitations of file access in browsers and the necessity of using the File API. However, there is no consensus on the best approach to achieve the participant's original goal without user interaction.

Contextual Notes

Participants note that the proposed methods depend on the context of running JavaScript in a browser versus other environments like Node.js, which may allow for different file access capabilities.

Who May Find This Useful

This discussion may be useful for developers working with JavaScript in browser environments, particularly those looking to handle file input and data processing in web applications.

Trying2Learn
Messages
375
Reaction score
57
TL;DR
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   Reactions: 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   Reactions: Trying2Learn
Thank you, everyone!
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 21 ·
Replies
21
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 28 ·
Replies
28
Views
4K
  • · Replies 33 ·
2
Replies
33
Views
5K
  • · Replies 8 ·
Replies
8
Views
6K
  • · Replies 5 ·
Replies
5
Views
2K