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

In summary, Jedishrfu's example will not work in a browser. You need to use the File API to access files on the web server.
  • #1
Trying2Learn
373
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
  • #3
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.
 
  • #4
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:
  • #5
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
  • #6
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
  • #7
Thank you, everyone!
 

What is an array in Javascript?

An array in Javascript is a data structure that is used to store a collection of values. It can hold any type of data, including numbers, strings, objects, and even other arrays.

How do I access elements in an array in Javascript?

To access elements in an array, you can use square brackets notation. For example, if you have an array called "fruits" with three elements, you can access the first element by using fruits[0], the second element by using fruits[1], and so on.

How can I add or remove elements in an array in Javascript?

To add elements to the end of an array, you can use the push() method. To remove elements from the end of an array, you can use the pop() method. To add elements to the beginning of an array, you can use the unshift() method. To remove elements from the beginning of an array, you can use the shift() method.

How can I loop through an array in Javascript?

To loop through an array, you can use a for loop or a forEach() method. Both methods allow you to perform a specific action on each element in the array.

How can I use Javascript to read and write to files?

In order to read and write to files using Javascript, you can use the fs module. This module provides methods for reading and writing files, as well as manipulating file paths and directories.

Similar threads

  • Programming and Computer Science
Replies
1
Views
542
  • Programming and Computer Science
Replies
4
Views
746
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
21
Views
5K
  • Programming and Computer Science
Replies
13
Views
1K
  • Programming and Computer Science
Replies
8
Views
879
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
Back
Top