How to read a local text file?

前端 未结 20 2347
北恋
北恋 2020-11-21 05:28

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

20条回答
  •  星月不相逢
    2020-11-21 06:04

    After the introduction of fetch api in javascript, reading file contents could not be simpler.

    reading a text file

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

    reading a json file

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

    Update 30/07/2018 (disclaimer):

    This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

    Update-2 (disclaimer):

    This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

提交回复
热议问题