What is the best way to retrieve JS arrays from a file once it has been opened?

UPDATE: Saving arrays with multiple dimensions is now possible in the following format:

var a = ["t1","a",["t2","a","b",["t3","a","b"],["t4","a","b","c",["t5","a","b"]],],["t6","a","b",["t7","a","b"]]];

This data can be saved to a file using a standard save file function that utilizes JSON.stringify(a) - excluding the "var a = " and the ";" parts. To later access this data, follow these steps:

<a id="nof"><label for="fid">Open Data</label></a>
<input id="fid" type="file" style="position: fixed; top: -100em" onchange="ReadFile(this)">

function ReadFile(input) {
    var output;

    if (input.files.length === 0) {
        output = 'No file selected';
        window.setTimeout(ReadFile, 1000);
        return;
    }

    var fr = new FileReader();
    fr.onload = function() {
        var data = fr.result;
        var array = new Int8Array(data);
        output = JSON.stringify(array, null, '  ');

        console.log(array); // output
    };
    fr.readAsArrayBuffer(input.files[0]);

I attempted to modify code from the post found at: Using FileReader.readAsArrayBuffer() on changed files in Firefox, but encountered difficulties assigning the data as a JS array variable. The console displays numbers due to int8 conversion.

The "output" variable results in:

{"0": 91,"1": 34,"2": 116,"3": 49,"4": 32,"5": 118,"6": 49,"7": 57,"8": 49,"9": 49,"10": 49,"11": 53,"12": 49,"13": 56,"14": 49,"15": 51,"16": 52,"17": 48,"18": 34,"19": 44,"20": 34,"21": 97,"22": 34,"23": 44,"24": 91,"25": 34,"26": 116,"27": 50,"28": 34,"29": 44,"30": 34,"31": 97,"32": 34,"33": 44,"34": 34,"35": 98,"36": 34,"37": 44,"38": 91,"39": 34,"40": 116,"41": 51,"42": 34,"43": 44,"44": 34,"45": 97,"46": 34,"47": 44,"48": 34,"49": 98,"50": 34,"51": 93,"52": 44,"53": 91,"54": 34,"55": 116,"56": 52,"57": 34,"58": 44,"59": 34,"60": 97,"61": 34,"62": 44,"63": 34,"64": 98,"65": 34,"66": 44,"67": 34,"68": 99,"69": 34,"70": 44,"71": 91,"72": 34,"73": 116,"74": 53,"75": 34,"76": 44,"77": 34,"78": 97,"79": 34,"80": 44,"81": 34,"82": 98,"83": 34,"84": 93,"85": 93,"86": 93,"87": 44,"88": 91,"89": 34,"90": 116,"91": 54,"92": 34,"93": 44,"94": 34,"95": 97,"96": 34,"97": 44,"98": 34,"99": 98,"100": 34,"101": 44,"102": 91,"103": 34,"104": 116,"105": 55,"106": 34,"107": 44,"108": 34,"109": 97,"110": 34,"111": 44,"112": 34,"113": 98,"114": 34,"115": 93,"116": 93,"117": 93}

To successfully assign file data as a JS array, additional adjustments are required.

***Efficiency-focused users can stick with the provided example array structure on the page without resorting to more intricate formats.

Answer №1

Displayed below are codes in an HTML div. To save them in an array, make the appropriate changes.

Give this a try:

function loadFile(file) {
   return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = x=> resolve(reader.result);
reader.readAsText(file);
})}

async function displayContent(input) {
  output.innerText= await loadFile(input.files[0]);
}

<input type="file" onchange="displayContent(this)"/>
<h3>File Content:</h3><pre id="output"></pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a component with a button that triggers the rendering of a different component?

I am struggling to implement an 'edit' button within a component that, upon clicking, should display a separate component known as a 'client edit modal'. I'm facing challenges in figuring out how to achieve this functionality. The ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

What is the procedure for combining individual objects into a single, unified group that maintains its structure?

I'm currently using fabricjs version 1.7.21 and I have a button that allows me to add text to the canvas. I am wondering how I can add a group of objects, such as multiple editable IText fields (as shown on the right side), to the canvas just like I c ...

Exploring MongoDB: executing find and findOne queries while utilizing nested array filtering

This task ended up being more challenging than I initially anticipated. Imagine a simple Posts collection where I need to display all posts along with only the comments that have not been deleted. In other words, how can I filter out deleted comments fro ...

Reactivity in Vue 3 with globalProperties

When attempting to migrate a Vue 2 plugin to Vue 3, I encountered an issue in the install function. In Vue 2, I had code that looked like this: install(Vue, options) { const reactiveObj = { // ... }; Vue.prototype.$obj = Vue.observable(reactiveO ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Incorporating Flash videos into an Angular HTML partial using AngularJS techniques

I've been struggling to embed a flash game in an angular HTML partial. The game loads without errors, but when I right click on the blank flash screen, it says "movie not loaded." I have tried using https://github.com/Pleasurazy/angularjs-media and an ...

Creating a new form upon a button click event dynamically in PHP

I have a situation where I've created dynamic buttons in PHP. When clicking on one of these dynamic buttons, I need to open a new form on the same homepage and prevent the page from refreshing. How can this issue be resolved? Below is the code that I ...

Hold off on continuing the script until the AJAX response has been received

In my script, I have two AJAX calls. The first one checks if a record exists in a database and should stop the script if it does. The second call submits a job. However, I am facing an issue where the job is being submitted before the first AJAX call retu ...

Adjust the height automatically in extjs hbox layout with this quick guide

When I try to dynamically set data in this layout, the layout doesn't resize properly and the final result looks like this. This is the code I'm currently using: win = Ext.create('widget.window', { title: 'Layout Window&apo ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

What is the best way to transfer the useState set state function to a child component in TypeScript?

Since delving into typescript, I've encountered an issue with passing a useState setter function. My parent component looks like this: const [word, setword] = useState('run') When passing props to the child component, it's done as fol ...

What are the steps for incorporating subelements into a fresh array?

My array consists of nested arrays, each containing only one value. I managed to flatten the array, but I can't shake the feeling that there might be a better way to do it. Is this approach optimal, or is there room for improvement? <?php $array ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Removing combinations of words in Python 3

Looking for a way to search a list of strings for a specific word combination in Python. If the combination is not found, I want to delete the entire string from the list. Does anyone know of a python list comprehension that can achieve this? word_list = ...

Tips on using b-table attributes thClass, tdClass, or class

<template> <b-table striped hover :fields="fields" :items="list" class="table" > </template> <style lang="scss" scoped> .table >>> .bTableThStyle { max-width: 12rem; text-overflow: ellipsis; } < ...

Received the item back from the database query

When I run the code below; var results = await Promise.all([ database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTERVAL 1 DAY;"), database.query("SELECT COUNT(amount) FROM transactions WHERE date >= now() - INTER ...

showcasing an assortment of images and selecting them with a click

I am working on a project that involves displaying random images and detecting if the user clicks on the correct image. I have defined an array of image IDs that I want to use for this purpose. private int[] imgId = new int[] { R.drawable.info_mna, ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...