简体   繁体   English

如何读取 txt 文件并将其保存在 html 中 javascript 中的数组中

[英]How to read txt file and save it in array in javascript in html

There are many solution to to this but I found few or none in javascript on html webpage.对此有很多解决方案,但我在 html 网页上的 javascript 中发现很少或没有。 I have a data file called sample.txt located where my html file is.我有一个名为 sample.txt 的数据文件,位于我的 html 文件所在的位置。 My goal is to load txt file into the array that can be used to create a table and displayed on html file.我的目标是将 txt 文件加载到可用于创建表格并显示在 html 文件上的数组中。 My sample.text file has the following data:我的 sample.text 文件有以下数据:

 sin 0.2 time 0.22222
 cos 0.3 time 0.43434
 tan 0.1 time 0.22221

I am new to Javascript and I admit that it is more difficult than other programming languages.我是 Javascript 的新手,我承认它比其他编程语言更难。 I am familiar with javascript in node.js mode but not in html mode.我熟悉 node.js 模式下的 javascript 但不熟悉 html 模式下的 javascript。 I managed to create html web page (as shown below) and display basics like text and numbers in script mode.我设法创建了 html web 页面(如下所示)并在脚本模式下显示文本和数字等基础知识。 I also managed to load txt file and display it after pressing a button in script mode.我还设法在脚本模式下按下按钮后加载 txt 文件并显示它。 This txt load method was the only method that worked for me.这个 txt 加载方法是唯一对我有用的方法。 require (js) method did not work nor import. require (js) 方法既不工作也不导入。 How do I create data array from this working mode?如何从这种工作模式创建数据数组?

Below is my complete code (corrected),以下是我的完整代码(已更正),

  <!DOCTYPE html>
  <html>
  <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
  <title>Read Text File</title> 
  </head> 

  <body> 
  <input type="file" name="inputfile"
        id="inputfile"> 
  <br> 

  <pre id="output"></pre> 
  <script>

  var file = document.getElementById('inputfile');

  file.addEventListener('change', () => {
  var txtArr = [];
  var fr = new FileReader();
  fr.onload = function() {
    // By lines
    var lines = this.result.split('\n');
    for (var line = 0; line < lines.length; line++) {
        txtArr = [...txtArr, ...(lines[line].split(" "))];
    }
   }
  fr.onloadend = function() {
    console.log(txtArr);
    document.getElementById('output').textContent=txtArr.join("");
    document.getElementById("output").innerHTML = txtArr[1]; 
    console.log(txtArr[1]);
  }

  fr.readAsText(file.files[0]);


  })

  </script>
  </body>
  </html> 

Using FileReader , get the string line by line and then split it and merge it into the resultArr as follows:使用FileReader逐行获取字符串,然后将其拆分并合并到 resultArr 中,如下所示:

 var file = document.getElementById('inputfile'); file.addEventListener('change', () => { var txtArr = []; var fr = new FileReader(); fr.onload = function() { // By lines var lines = this.result.split('\n'); for (var line = 0; line < lines.length; line++) { txtArr = [...txtArr, ...(lines[line].split(" "))]; } } fr.onloadend = function() { console.log(txtArr); document.getElementById('output').textContent=txtArr.join(""); } fr.readAsText(file.files[0]); })
 <!DOCTYPE html> <html> <head> <title>Read Text File</title> </head> <body> <input type="file" name="inputfile" id="inputfile"> <br> <pre id="output"></pre> </body> </html>

The reason the other methods didn't work is because Javascript does not have access to the filesystem.其他方法不起作用的原因是因为 Javascript 无权访问文件系统。 You need a server side language for this, like NodeJS.为此,您需要一种服务器端语言,例如 NodeJS。

Anyway, here's some pure Javascript code that lets you load text files, split result into a text array for each line and split those again to have data arrays for each line of data.无论如何,这里有一些纯 Javascript 代码,可让您加载文本文件,将结果拆分为每行的文本数组,然后再次拆分这些数据以获得每行数据的数据 arrays。 As a little bonus, I also added a method to download everything in a text file again:作为一个小奖励,我还添加了一种方法来再次下载文本文件中的所有内容:

function loadFile(input, onloadCallback){
    const fr = new FileReader();

    fr.onload = onloadCallback;

    fr.readAsText(input);
}

/* Save file and force download */
function saveFile(data, fileName){
    const blob = new Blob([data], {type: 'text/csv'});
    if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, fileName);
    } else {
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob);
        elem.download = fileName;        
        document.body.appendChild(elem);
        elem.click();
        document.body.removeChild(elem);
    }
}

/* Working with text files */
function openFile(ev){
    loadFile(ev.target.files[0], function(e) {
        // Get all the text as a string
        const result = e.target.result;

        // Make array out of result for each line
        const textArray = result.split("\r\n");

        // How to add new lines to the array if you want
        textArray.push("tan 0.2 time 0.23641");

        // Create dataArray for each line
        let dataArray = [];

        for(let i = 0; i < textArray.length; i++){
            const data = textArray[i].split(" ");

            dataArray.push(data);
        }

        // dataArray now contains arrays for each line of data
        console.log(dataArray);

        // Here's how you'd put a normal array back into a string
        const newString = textArray.join("\r\n");

        // Finally a way to download a file with the new string inside it
        saveFile(newString, 'test.txt');
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM