2016-04-28 24 views
5

Ho sul mio server web uno script JS che voglio essere in grado di leggere i file. mio filesystem è come questo:Leggere un file lato server usando JavaScript

> Root 
index.html 
read.js 
> files 
    file.txt 

In questo esempio, il file "file.txt" conterrà la semplice parola "Ciao"

con JavaScript, voglio essere in grado di fare una funzione, per esempio:

function read (path) { 
    //Stuff to read the file with specified path 
    var content = //whatever the content is 
    return content; 
} 

E poi essere in grado di chiamare con:

var file = read("/files/file.txt") 

E poi quando faccio

alert(file) 

Si aprirà con/te avviso con "Ciao", il contenuto di file.txt.

C'è un modo in cui sarei in grado di farlo?

risposta

2

Quello che stai cercando è XMLHttpRequest.

+0

Sareste in grado di dire/mostrarmi come utilizzare XMLHttpRequest per raggiungere questo obiettivo? –

+0

Letteralmente il primo esempio di codice su https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest è quasi esattamente quello che stai chiedendo. Basta sostituire l'URL con il tuo. –

0

Non è così semplice come sembra e si dovrà fare qualche ricerca su server vs client.

Non è possibile leggere i dati lato server tramite Javascript a meno che non si disponga di una connessione al server. Qualunque codice Javascript che gira sul browser del client rimarrà sul proprio browser, anche se entrambi vengono eseguiti sullo stesso computer. Quello di cui hai bisogno è un modo per far comunicare al client (in questo caso, il sito Web html + javascript) con il server.

Ci sono infiniti modi per farlo, ma il più semplice è attraverso una richiesta GET a un server che sta servendo quel file di testo.

Prova a cercare file statici con NGINX o forse qualcosa come NodeJS, a seconda di ciò che soddisfa le tue esigenze. Da lì, creare un endpoint GET a cui si connetterà il tuo Javascript tramite XMLHttpRequest (come @MattW.

0

Questa è un'attività molto semplice se si utilizza JQuery. L'esempio seguente eseguirà una richiesta HTTP GET (utilizzando XMLHttpRequest.as di cui sopra) e inserirà il contenuto in un oggetto DOM HTML con l'ID di "risultato" . Avvierà anche una finestra di avviso una volta completato il caricamento.

$("#result").load("files/file.txt", function() { 
    alert("Load was performed."); 
}); 
0

si vuole essere utilizzando XMLHttpRequest, come Gabriel ha suggerito.

È seriamente necessario leggerlo, poiché è molto configurabile e è necessario comprendere il flusso di lavoro per implementarlo. All'inizio incontrerai dei problemi, se sei uno scripting di origine incrociata.

Ecco un esempio ho preso in giro per voi:

<span id="placeholder"></span> 
 
<script> 
 
    var xhr = new XMLHttpRequest(); 
 
    xhr.onreadystatechange = function() { 
 
     if (xhr.readyState == 4 && xhr.status == 200) { 
 
      document.getElementById('placeholder').innerHTML = xhr.responseText; 
 
     } 
 
    } 
 
    xhr.open('GET', 'test.html'); 
 
    xhr.send(); 
 
</script>

+0

Sarei in grado di impostare una variabile per il contenuto nello stesso modo in cui sarei in grado di impostare l'html interno di #placeholder? –

+0

Sì, collegalo all'oggetto 'window'. 'window.myVar = xhr.responseText' –

+1

Si presume che il file 'file.txt' sia effettivamente servito da qualcosa. Non c'è modo di accedere al file da XHR se non viene nemmeno aperto al "mondo esterno" – SamuelN

2

Ecco una pagina web di esempio per voi:

http://sealevel.info/test_file_read.html

Ecco il codice javascript:

// Synchronously read a text file from the web server with Ajax 
// 
// The filePath is relative to the web page folder. 
// Example: myStuff = loadFile("Chuuk_data.txt"); 
// 
// You can also pass a full URL, like http://sealevel.info/Chuuk1_data.json, but there 
// might be Access-Control-Allow-Origin issues. I found it works okay in Firefox, Edge, 
// or Opera, and works in IE 11 if the server is configured properly, but in Chrome it only 
// works if the domains exactly match (and note that "xyz.com" & "www.xyz.com" don't match). 
// Otherwise Chrome reports an error: 
// 
// No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sealevel.info' is therefore not allowed access. 
// 
// That happens even when "Access-Control-Allow-Origin *" is configured in .htaccess, 
// and even though I verified the headers returned (you can use a header-checker site like 
// http://www.webconfs.com/http-header-check.php to check it). I think it's a Chrome bug. 
function loadFile(filePath) { 
    var result = null; 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.open("GET", filePath, false); 
    xmlhttp.send(); 
    if (xmlhttp.status==200) { 
    result = xmlhttp.responseText; 
    } 
    return result; 
} 
Problemi correlati