Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

javascript - Node.JS readFileSync() function

index.js

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>

I'm trying to store the file path in a variable and then feed it ti readFileSync() function, but this gives me fllowing error in the 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:
odejsfile_upload
outer.js:7:15)
    at Server.onRequest (D:
odejsfile_uploadserver.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)

but if I enter the path "D:/nodejs/file_upload/view/index.html" in the function directly then it shows me the page in the browser.

I stored the index.html file in the view folder

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EISDIR error occurs when you try to open a file, but the path given is a directory. See related question and answer: Using Node.js I get, "Error: EISDIR, read".

To debug this I would log to console the variable directpath and I would assume that it is pointing to a directory, not a file. Correctly setting this variable to the intended path should solve your problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...