2014-09-17 7 views
11

index.jsNode.JS readFileSync funzione()

var server = require("./server"); 
var router = require("./router"); 

server.start(router.route); 

server.js

//Script to start a server 

var http = require("http"); 
var url = require("url"); 
var fs = require("fs"); 

function start(route) { 
    function onRequest(request, response) { 

     var pathname = url.parse(request.url).pathname; 

     route(pathname, response, fs); 

    } 

    http.createServer(onRequest).listen(8888); 
    console.log("Server has started."); 
} 

exports.start = start; 

router.js

function route(pathname, response, fs) { 

    var regex = new RegExp('^/view/?$'); 

    var directpath = "D:/nodejs/file_upload" + pathname; 

    var voo = fs.readFileSync(directpath); 

    if(regex.test(pathname)){ 

     response.writeHead(200, {"Content-Type": "text/html"}); 
     console.log("About to route a request for " + pathname); 
     response.end(voo); 

    } else{ 

     response.writeHead(404); 
     response.end("<br/>404, file not found"); 

    } 
} 

exports.route = route; 

index.html

<!DOCTYPE html> 
<html> 
    <body> 
     <p>Hello My friend </p> 
    </body> 
</html> 

Sto cercando di memorizzare il percorso del file in una variabile e quindi di inviarlo alla funzione readFileSync(), ma questo mi dà un errore nella console.

Error: EISDIR, illegal operation on a directory 
    at Object.fs.readSync (fs.js:487:19) 
    at Object.fs.readFileSync (fs.js:326:28) 
    at route (D:\nodejs\file_upload\router.js:7:15) 
    at Server.onRequest (D:\nodejs\file_upload\server.js:15:6) 
    at Server.emit (events.js:98:17) 
    at HTTPParser.parser.onIncoming (http.js:2108:12) 
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23 
) 
    at Socket.socket.ondata (http.js:1966:22) 
    at TCP.onread (net.js:527:27) 

ma se entro il percorso "D: /nodejs/file_upload/view/index.html" nella funzione direttamente poi mi mostra la pagina nel browser.

ho memorizzato il file index.html nella cartella vista

+0

Forse provate 'fs.readdir()' e passate in rassegna l'array che restituisce? – CaffeineAddiction

+3

possibile duplicato di [Uso di Node.js Ottengo, "Errore: EISDIR, leggi"] (http://stackoverflow.com/questions/20417118/using-node-js-i-get-error-eisdir-read) –

+3

Molto probabilmente, stai cercando di leggere 'D:/nodejs/file_upload/view' invece di' D:/nodejs/file_upload/view/index.html'. –

risposta

52

EISDIR errore si verifica quando si tenta di aprire un file, ma il percorso è una directory data. Vedi domande e risposte correlate: Using Node.js I get, "Error: EISDIR, read".

Per eseguire il debug di questo, vorrei accedere alla console della variabile directpath e suppongo che stia puntando a una directory, non a un file. Impostare correttamente questa variabile sul percorso desiderato dovrebbe risolvere il tuo problema.

Problemi correlati