Node.JS readFileSync()函数

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文件存储在视图文件夹中

回答:

EISDIR当您尝试打开文件时出现错误,但是给定的路径是目录。

为了调试它,我将登录以控制台变量,directpath并假定它指向目录,而不是文件。将此变量正确设置为预期路径应该可以解决您的问题。

以上是 Node.JS readFileSync()函数 的全部内容, 来源链接: utcz.com/qa/434684.html

回到顶部