Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    • Bàn luận Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
    • HTML 5 cung cấp một cách tiêu chuẩn để tương tác với các tệp cục bộ với sự trợ giúp của API tệp. API tệp cho phép tương tác với các tệp đơn, cũng như blob. API FileReader có thể được sử dụng để đọc một tệp không đồng bộ trong sự hợp tác với xử lý sự kiện JavaScript. Tuy nhiên, tất cả các trình duyệt không có hỗ trợ HTML 5, vì vậy điều quan trọng là phải kiểm tra khả năng tương thích của trình duyệt trước khi sử dụng API tệp. Có bốn phương thức sẵn có trong API Filereader để đọc các tệp cục bộ: Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
    • FileReader.ReadAsArrayBuffer (): Đọc nội dung của tệp đầu vào được chỉ định. Thuộc tính kết quả chứa một ArrayBuffer đại diện cho dữ liệu tệp. Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
    • FileReader.ReadAsBinaryString (): Đọc nội dung của tệp đầu vào được chỉ định. Thuộc tính kết quả chứa dữ liệu nhị phân thô từ tệp dưới dạng chuỗi. Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.

    FileReader.ReadAsDataurl (): Đọc nội dung của tệp đầu vào được chỉ định. Thuộc tính kết quả chứa một URL đại diện cho dữ liệu tệp..txt file.

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    7

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    8

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    9

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    1

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    2

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    3

    FileReader.Readastext (): Đọc nội dung của tệp đầu vào được chỉ định. Thuộc tính kết quả chứa nội dung của tệp dưới dạng chuỗi văn bản. Phương thức này có thể lấy phiên bản mã hóa làm đối số thứ hai (nếu được yêu cầu). Mã hóa mặc định là UTF-8.

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    0
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    8
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    2

    Trong trường hợp này, chúng tôi đang sử dụng phương thức filereader.readastext () để đọc tệp .txt cục bộ.

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    6
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    7
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    8

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0

    ...
    0

    ...
    1
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    2


    ...
    3

    ...
    4

    ...
    5

    ...
    6

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9

    ...
    8

    ...
    9
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    0
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    1
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    2

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    5
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    6
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    7
    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    8

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    9
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    1
    
    
    1

    
    
    2

    ...
    4
    
    
    4

    ...
    6

    
    
    6
    
    
    7

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9
    
    
    9

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9
    
    
    1
    
    
    2
    
    
    3


    ...
    3
    
    
    5

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0
    
    
    7

    
    
    8

    
    
    9

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    0
    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };
    4

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    
    9
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    4
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    5
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    6
    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    7


    Tôi đang cố gắng ghi lại một trình đọc tệp văn bản đơn giản bằng cách tạo một hàm có trong đường dẫn tệp và chuyển đổi từng dòng văn bản thành một mảng char, nhưng nó không hoạt động.

    function readTextFile() {
      var rawFile = new XMLHttpRequest();
      rawFile.open("GET", "testing.txt", true);
      rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4) {
          var allText = rawFile.responseText;
          document.getElementById("textSection").innerHTML = allText;
        }
      }
      rawFile.send();
    }
    

    Điều gì đang xảy ra ở đây?

    Điều này vẫn không có vẻ hoạt động sau khi thay đổi mã một chút từ bản sửa đổi trước đó và bây giờ nó mang lại cho tôi ngoại lệ

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    00 101.

    Tôi đã thử nghiệm điều này trên Firefox và nó hoạt động, nhưng trong Google Chrome, nó sẽ không hoạt động và nó tiếp tục cho tôi một ngoại lệ 101. Làm thế nào tôi có thể làm cho nó hoạt động không chỉ Firefox mà còn trên các trình duyệt khác (đặc biệt là Chrome )?

    Ggorlen

    37.2K7 Huy hiệu vàng61 Huy hiệu bạc79 Huy hiệu đồng7 gold badges61 silver badges79 bronze badges

    Đã hỏi ngày 21 tháng 1 năm 2013 lúc 20:14Jan 21, 2013 at 20:14

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    3

    Bạn cần kiểm tra trạng thái 0 (như khi tải các tệp cục bộ với

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    00, bạn không nhận được trạng thái được trả về vì nó không phải từ
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    02)

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    

    Và chỉ định

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    03 trong tên tệp của bạn:

    readTextFile("file:///C:/your/path/to/file.txt");
    

    Themroc

    4752 Huy hiệu bạc5 Huy hiệu Đồng2 silver badges5 bronze badges

    Đã trả lời ngày 21 tháng 1 năm 2013 lúc 20:20Jan 21, 2013 at 20:20

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Majid Laissimajid LaissiMajid Laissi

    18.7K19 Huy hiệu vàng65 Huy hiệu bạc105 Huy hiệu Đồng19 gold badges65 silver badges105 bronze badges

    29

    Sau khi giới thiệu API tìm nạp trong JavaScript, việc đọc nội dung tệp không thể đơn giản hơn.

    Đọc một tệp văn bản

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    

    Đọc tệp JSON

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    

    Cập nhật 30/07/2018 (Tuyên bố miễn trừ trách nhiệm):

    Kỹ thuật này hoạt động tốt trong Firefox, nhưng có vẻ như việc triển khai ____104 của Chrome không hỗ trợ chương trình URL ____105 vào ngày viết bản cập nhật này (được thử nghiệm trong Chrome 68).Firefox, but it seems like Chrome's

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    04 implementation does not support
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    05 URL scheme at the date of writing this update (tested in Chrome 68).

    Cập nhật-2 (Tuyên bố miễn trừ trách nhiệm):

    Kỹ thuật này không hoạt động với Firefox trên phiên bản 68 (ngày 9 tháng 7 năm 2019) vì lý do (bảo mật) tương tự như Chrome:

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    06. Xem https://developer.mozilla.org/en-us/docs/web/http/cors/errors/corsrequestnothttp.Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome:
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    06. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

    Olivierm

    2.59023 Huy hiệu bạc36 Huy hiệu đồng23 silver badges36 bronze badges

    Đã trả lời ngày 9 tháng 9 năm 2017 lúc 9:42Sep 9, 2017 at 9:42

    11

    Ghé thăm JavaScripture! Và đi phần readastext và thử ví dụ. Bạn sẽ có thể biết làm thế nào chức năng readastext của filereader hoạt động.readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };

    ...

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Teocci

    5,8621 Huy hiệu vàng42 Huy hiệu bạc42 Huy hiệu đồng1 gold badge42 silver badges42 bronze badges

    Đã trả lời ngày 20 tháng 3 năm 2015 lúc 21:30Mar 20, 2015 at 21:30

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Amit chaurasiaamit chaurasiaAmit Chaurasia

    1.4192 huy hiệu vàng11 Huy hiệu bạc8 Huy hiệu đồng2 gold badges11 silver badges8 bronze badges

    3

    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    
    

    Đã trả lời ngày 22 tháng 8 năm 2017 lúc 10:46Aug 22, 2017 at 10:46

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    3

    Giải pháp hiện đại:

    Sử dụng

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    07 như sau:

    
    

    Khi người dùng tải lên một tệp văn bản thông qua đầu vào đó, nó sẽ được đăng nhập vào bảng điều khiển. Đây là bản demo JSBIN đang hoạt động.

    Đây là phiên bản dài dòng hơn:

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    0

    Hiện tại (tháng 1 năm 2020) Điều này chỉ hoạt động trong Chrome và Firefox, hãy kiểm tra tại đây để tương thích nếu bạn đang đọc điều này trong tương lai: https://developer.mozilla.org/en-us/docs/web/api/blob/text

    Trên các trình duyệt cũ, điều này sẽ hoạt động:

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    1

    Liên quan: Kể từ tháng 9 năm 2020, API hệ thống tệp gốc mới có sẵn trong Chrome và Edge trong trường hợp bạn muốn truy cập đọc vĩnh viễn (và thậm chí là ghi quyền truy cập) vào tệp do người dùng chọn.

    2

    Có JS có thể đọc các tệp cục bộ (xem Filereader ()) nhưng không tự động: Người dùng phải chuyển tệp hoặc danh sách các tệp cho tập lệnh với HTML

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    08.

    Sau đó, với JS, có thể xử lý (xem ví dụ) tệp hoặc danh sách các tệp, một số thuộc tính của chúng và nội dung tệp hoặc tệp.

    Những gì JS không thể làm vì lý do bảo mật là tự động truy cập (không có đầu vào của người dùng) vào hệ thống tập tin của máy tính.

    Để cho phép JS truy cập vào FS cục bộ là cần tự động để tạo không phải là tệp HTML với JS bên trong nó mà là một tài liệu HTA.

    Một tệp HTA có thể chứa JS hoặc VBS bên trong nó.

    Nhưng thực thi HTA sẽ chỉ hoạt động trên các hệ thống Windows.

    Đây là hành vi trình duyệt tiêu chuẩn.

    Ngoài ra, Google Chrome đã làm việc tại API FS, thông tin thêm ở đây: http://www.html5rocks.com/en/tutorials/file/filesystem/

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Isherwood

    54,8K16 Huy hiệu vàng108 Huy hiệu bạc149 Huy hiệu đồng16 gold badges108 silver badges149 bronze badges

    Đã trả lời ngày 29 tháng 1 năm 2016 lúc 3:31Jan 29, 2016 at 3:31

    SparrowsparrowSparrow

    3313 Huy hiệu bạc3 Huy hiệu đồng3 silver badges3 bronze badges

    0

    Sử dụng hàm tìm nạp và async

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    2

    Đã trả lời ngày 8 tháng 1 năm 2019 lúc 13:15Jan 8, 2019 at 13:15

    barro32barro32barro32

    2.22420 huy hiệu bạc34 huy hiệu đồng20 silver badges34 bronze badges

    2

    Hãy thử tạo hai chức năng:

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    3

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Bill Bell

    20.4K5 Huy hiệu vàng42 Huy hiệu bạc57 Huy hiệu đồng5 gold badges42 silver badges57 bronze badges

    Đã trả lời ngày 16 tháng 10 năm 2013 lúc 23:29Oct 16, 2013 at 23:29

    1

    Có thể bạn đã thử nó, nhập "Sai" như sau:

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    4

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    A-Sharabiani

    16.4K16 Huy hiệu vàng106 Huy hiệu bạc126 Huy hiệu Đồng16 gold badges106 silver badges126 bronze badges

    Đã trả lời ngày 26 tháng 11 năm 2013 lúc 12:17Nov 26, 2013 at 12:17

    Momenmomenmomen

    1291 Huy hiệu bạc3 Huy hiệu đồng1 silver badge3 bronze badges

    Ví dụ khác - người đọc của tôi với lớp Filereader

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    5

    Đã trả lời ngày 19 tháng 2 năm 2015 lúc 15:35Feb 19, 2015 at 15:35

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    WebSkyWebskywebsky

    2.9521 Huy hiệu vàng33 Huy hiệu bạc29 Huy hiệu đồng1 gold badge33 silver badges29 bronze badges

    1

    Điều này có thể giúp,

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    6

    Đã trả lời ngày 18 tháng 11 năm 2016 lúc 15:20Nov 18, 2016 at 15:20

    Sameera R.Sameera R.Sameera R.

    4.2161 Huy hiệu vàng33 Huy hiệu bạc51 Huy hiệu đồng1 gold badge33 silver badges51 bronze badges

    Các cuộc gọi AJAX cục bộ trong Chrome không được hỗ trợ do chính sách có nguồn gốc.

    Thông báo lỗi trên Chrome như thế này: "Yêu cầu gốc chéo không được hỗ trợ cho các sơ đồ giao thức: HTTP, Dữ liệu, Chrome, Mở rộng Chrome, HTTPS."

    Điều này có nghĩa là Chrome tạo ra một đĩa ảo cho mọi miền để giữ các tệp được phục vụ bởi miền bằng cách sử dụng các giao thức HTTP/HTTPS. Bất kỳ quyền truy cập vào các tệp bên ngoài đĩa ảo này đều bị hạn chế theo cùng một chính sách gốc. Các yêu cầu và phản hồi của AJAX xảy ra trên HTTP/HTTPS, do đó sẽ không hoạt động cho các tệp cục bộ.

    Firefox không đặt hạn chế như vậy, do đó mã của bạn sẽ hoạt động hạnh phúc trên Firefox. Tuy nhiên, có những cách giải quyết cho Chrome quá: xem ở đây.

    Đã trả lời ngày 26 tháng 12 năm 2018 lúc 12:12Dec 26, 2018 at 12:12

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    1

    Thêm vào một số câu trả lời trên, giải pháp sửa đổi này đã làm việc cho tôi.

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    7

    Hốt tức

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    8

    Hốt tức

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    9

    Đã trả lời ngày 31 tháng 12 năm 2018 lúc 19:50Dec 31, 2018 at 19:50

    FabiifabiiFabii

    3.75013 huy hiệu vàng49 Huy hiệu bạc89 Huy hiệu đồng13 gold badges49 silver badges89 bronze badges

    readTextFile("file:///C:/your/path/to/file.txt");
    
    0

    - Đọc văn bản tệp từ JavaScript- Bản ghi bảng điều khiển văn bản từ tệp bằng JavaScript- Google Chrome và Mozilla Firefox
    - Console log text from file using javascript
    - Google chrome and mozilla firefox

    Trong trường hợp của tôi, tôi có cấu trúc tệp này:

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Kết quả console.log:

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Đã trả lời ngày 18 tháng 1 năm 2019 lúc 9:38Jan 18, 2019 at 9:38

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Nadir Hamidounadir Hamidounadir hamidou

    4232 Huy hiệu vàng7 Huy hiệu bạc18 Huy hiệu đồng2 gold badges7 silver badges18 bronze badges

    1

    Làm thế nào để đọc một tập tin cục bộ?

    Bằng cách sử dụng điều này, bạn sẽ tải một tệp bằng loadtext () thì js sẽ không đồng bộ chờ cho đến khi tệp được đọc và tải sau đó nó sẽ vượt qua chức năng readtext () cho phép bạn tiếp tục với logic js bình thường của bạn Chặn trên hàm LoadText () trong trường hợp bất kỳ lỗi nào phát sinh) nhưng đối với ví dụ này, tôi giữ nó ở mức tối thiểu.

    readTextFile("file:///C:/your/path/to/file.txt");
    
    1

    Đã trả lời ngày 3 tháng 10 năm 2019 lúc 13:33Oct 3, 2019 at 13:33

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    D.SnapD.SnapD.Snap

    1.5641 Huy hiệu vàng20 Huy hiệu bạc14 Huy hiệu đồng1 gold badge20 silver badges14 bronze badges

    1

    Nếu bạn muốn nhắc người dùng chọn tệp, thì hãy đọc nội dung của nó:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    2

    Usage:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    3

    Đã trả lời ngày 16 tháng 12 năm 2020 lúc 15:13Dec 16, 2020 at 15:13

    Yayayayayaya

    6,8491 Huy hiệu vàng32 Huy hiệu bạc34 Huy hiệu đồng1 gold badge32 silver badges34 bronze badges

    readTextFile("file:///C:/your/path/to/file.txt");
    
    4

    Đã trả lời ngày 22 tháng 2 năm 2018 lúc 7:41Feb 22, 2018 at 7:41

    Nhận dữ liệu tệp cục bộ trong tải JS (Data.js):

    readTextFile("file:///C:/your/path/to/file.txt");
    
    5

    Tệp dữ liệu.js như:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    6

    QueryString unixtime Dynamic ngăn chặn bộ nhớ cache.

    AJ hoạt động trong web http: //.

    Đã trả lời ngày 26 tháng 4 năm 2019 lúc 5:20Apr 26, 2019 at 5:20

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    1

    Chức năng này được thực hiện cho các trình duyệt và hộp thoại Picker Picker mở và sau khi lựa chọn người dùng, hãy đọc tệp dưới dạng chức năng gọi lại nhị phân và gọi lại với dữ liệu đọc:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    7

    Và sử dụng nó như thế này:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    8

    Đã trả lời ngày 19 tháng 12 năm 2021 lúc 8:24Dec 19, 2021 at 8:24

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    MSSMSSMSS

    3.38223 Huy hiệu bạc28 Huy hiệu đồng23 silver badges28 bronze badges

    1

    Đây là một câu hỏi cũ nhưng có hai ý tưởng chính mà chúng ta phải rõ ràng. Chúng ta có muốn đọc toàn bộ tập tin hoặc lấy nó từng dòng không?

    Teo, tôi muốn lấy toàn bộ tập tin và xử lý nó sau.

    Được rồi, điều đó rất dễ dàng, chúng tôi chỉ gọi

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    09 (hãy nhớ rằng
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    09 giả sử rằng tệp được mã hóa là
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    11) và xử lý các tệp như thế này:

    readTextFile("file:///C:/your/path/to/file.txt");
    
    9
    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    0

    Những gì về từng dòng? Điều đó là có thể?.

    Vâng, Padawan trẻ của tôi, điều đó cũng có thể

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    1
    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    0

    Đã trả lời ngày 28 tháng 9 lúc 6:36Sep 28 at 6:36

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    TeoccitocciTeocci

    5,8621 Huy hiệu vàng42 Huy hiệu bạc42 Huy hiệu đồng1 gold badge42 silver badges42 bronze badges

    Bạn có thể nhập thư viện của tôi:

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    3

    Sau đó, hàm

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    13 sẽ trả về tệp đã tải lên

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    4

    Xin lưu ý: Trên Google Chrome nếu mã HTML là cục bộ, các lỗi sẽ xuất hiện, nhưng lưu mã HTML và các tệp trực tuyến sau đó chạy tệp HTML trực tuyến hoạt động.

    Đã trả lời ngày 3 tháng 1 năm 2019 lúc 23:40Jan 3, 2019 at 23:40

    Để đọc một văn bản tệp cục bộ thông qua

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    14 bằng Chrome, trình duyệt Chrome nên chạy với đối số
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    15 để cho phép JavaScript truy cập tệp cục bộ, sau đó bạn có thể đọc nó bằng
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    
    16 như sau:

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    5

    Đã trả lời ngày 7 tháng 1 năm 2019 lúc 9:56Jan 7, 2019 at 9:56

    Hướng dẫn how do i read a .text file in javascript? - làm cách nào để đọc tệp .text trong javascript?

    Ali Ezzat Odehali Ezzat OdehAli Ezzat Odeh

    2.0731 Huy hiệu vàng17 Huy hiệu bạc17 Huy hiệu đồng1 gold badge17 silver badges17 bronze badges

    Tôi biết, tôi đến muộn trong bữa tiệc này. Hãy để tôi chỉ cho bạn những gì tôi có.

    Đây là một cách đọc đơn giản của tệp văn bảnsimple reading of text file

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    
    6

    Tôi hi vọng cái này giúp được.

    Đã trả lời ngày 16 tháng 3 năm 2020 lúc 9:50Mar 16, 2020 at 9:50

    1

    Bạn có thể đọc một tệp văn bản trong JavaScript không?

    Để đọc một tệp, hãy sử dụng Filereader, cho phép bạn đọc nội dung của một đối tượng tệp vào bộ nhớ. Bạn có thể hướng dẫn Filereader đọc một tệp dưới dạng bộ đệm mảng, URL dữ liệu hoặc văn bản.use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text.

    Làm cách nào để nhập tệp văn bản vào JavaScript?

    Nhập mô hình FS trong chương trình và sử dụng các chức năng để đọc văn bản từ các tệp trong hệ thống ...
    Đầu vào.....
    Script.js: ....
    Thay vì chuyển đổi bộ đệm thành văn bản bằng hàm toString, cũng trực tiếp lấy dữ liệu thành định dạng văn bản ..

    Làm cách nào để mở một tệp bằng JavaScript?

    Cách mở một tập tin trong JavaScript..
    Nhấp chuột phải vào tệp HTML bạn muốn sử dụng để mở tệp.Nhấp vào "Mở với", sau đó bấm đúp vào trình chỉnh sửa JavaScript ưa thích.....
    Tạo chức năng JavaScript.....
    Thêm chức năng vào nút "Duyệt" trên trang web.....
    Lưu tệp và mở nó trong trình duyệt web mặc định của bạn ..

    Làm cách nào để đọc một tệp văn bản trong HTML?

    HTML 5 cung cấp một cách tiêu chuẩn để tương tác với các tệp cục bộ với sự trợ giúp của API tệp.API tệp cho phép tương tác với các tệp đơn, cũng như blob.API FileReader có thể được sử dụng để đọc một tệp không đồng bộ trong sự hợp tác với xử lý sự kiện JavaScript.The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.