gpt4 book ai didi

javascript - Node.JS readFileSync() 函数

转载 作者:IT老高 更新时间:2023-10-28 23:13:05 34 4
gpt4 key购买 nike

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;

路由器.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 文件存储在 View 文件夹中

最佳答案

EISDIR 尝试打开文件时发生错误,但给出的路径是目录。查看相关问答:Using Node.js I get, "Error: EISDIR, read" .

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

关于javascript - Node.JS readFileSync() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25883775/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com