Node.JS readFileSync()函数

时间:2014-09-17 06:32:30

标签: javascript node.js

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>

我正在尝试将文件路径存储在变量中,然后将其提供给readFileSync()函数,但这会让我在控制台中出现错误。

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)

但如果我直接在函数中输入路径“D:/nodejs/file_upload/view/index.html”,那么它会在浏览器中显示该页面。

我将index.html文件存储在视图文件夹

1 个答案:

答案 0 :(得分:57)

当您尝试打开文件时出现

EISDIR错误,但给出的路径是一个目录。请参阅相关问题和答案:Using Node.js I get, "Error: EISDIR, read"

要调试这个,我会登录控制变量directpath,我会认为它指向的是目录,而不是文件。正确地将此变量设置为预期路径可以解决您的问题。