1

when i debug this code in to chrome console then its not show any output or alert! please help me to complete this code! i need to get read my read.txt file text in to console.log.... the code was i try one is shows below.

 function loadText() {
    fetch('C:\Windows\Temp\read.txt')
    .then(function(response){
        return response.text();
    })
    .then(function(data){
        console.log(data);  
        alert(data)      
    })
    .catch(function(error){
        console.log(error);
        alert(data)      
    })
}
Mirshad Rifas
  • 11
  • 1
  • 5
  • 1
    The Chrome console likely does not allow you to read files from your (local) file system. Maybe there is a flag in the settings to allow that option. However, it's a big security risk to allow the Chrome console to read your local files. Malicious browser extensions could leverage this to gain access to files they're not supposed to. – nbokmans Nov 18 '20 at 09:20
  • if its possble when i disable chrome web security? – Mirshad Rifas Nov 18 '20 at 09:32

2 Answers2

0
Try below code and indicate your directory like below

async function fetchText() {
    let response = await fetch('../demo.txt');

    console.log(response.status); // 200
    console.log(response.statusText); // OK

    if (response.status === 200) {
        let data = await response.text();
        console.log(data);
        // handle data
    }
}

fetchText();
Shantun Parmar
  • 432
  • 2
  • 13
  • i tried like this but its get error! please help.... async function fetchText() { let response = await fetch('C:\Windows\Temp\read.txt'); console.log(response.status); // 200 console.log(response.statusText); // OK if (response.status === 200) { let data = await response.text(); console.log(data); // handle data } } fetchText(); – Mirshad Rifas Nov 18 '20 at 09:36
  • change C:\Windows\Temp\read.txt to ../../yourdirectory, Its' working for me – Shantun Parmar Nov 18 '20 at 09:46
0

This seems like a duplicate of this issue - AJAX request to local file system not working in Chrome?

The problems are the same, however you are using the fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) not an XMLHttp request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)

When i run loadText i get the following error:-

Fetch API cannot load . URL scheme must be "http" or "https" for CORS request.

You cannot make requests to the filesystem in Chrome. However you can disable Chrome security using flags (--allow-file-access-from-files) see - Allow Google Chrome to use XMLHttpRequest to load a URL from a local file however this is not advised.

You will also need to update your path in the fetch function by prefixing with file:/// this tells it to look in the file system, and changed the protocol from http or https.

Ben F Lodge
  • 21
  • 1
  • 4