index.js
JavaScript
x
5
1
var server = require("./server");
2
var router = require("./router");
3
4
server.start(router.route);
5
server.js
JavaScript
1
21
21
1
//Script to start a server
2
3
var http = require("http");
4
var url = require("url");
5
var fs = require("fs");
6
7
function start(route) {
8
function onRequest(request, response) {
9
10
var pathname = url.parse(request.url).pathname;
11
12
route(pathname, response, fs);
13
14
}
15
16
http.createServer(onRequest).listen(8888);
17
console.log("Server has started.");
18
}
19
20
exports.start = start;
21
router.js
JavaScript
1
24
24
1
function route(pathname, response, fs) {
2
3
var regex = new RegExp('^/view/?$');
4
5
var directpath = "D:/nodejs/file_upload" + pathname;
6
7
var voo = fs.readFileSync(directpath);
8
9
if(regex.test(pathname)){
10
11
response.writeHead(200, {"Content-Type": "text/html"});
12
console.log("About to route a request for " + pathname);
13
response.end(voo);
14
15
} else{
16
17
response.writeHead(404);
18
response.end("<br/>404, file not found");
19
20
}
21
}
22
23
exports.route = route;
24
index.html
JavaScript
1
7
1
<!DOCTYPE html>
2
<html>
3
<body>
4
<p>Hello My friend </p>
5
</body>
6
</html>
7
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.
JavaScript
1
12
12
1
Error: EISDIR, illegal operation on a directory
2
at Object.fs.readSync (fs.js:487:19)
3
at Object.fs.readFileSync (fs.js:326:28)
4
at route (D:nodejsfile_uploadrouter.js:7:15)
5
at Server.onRequest (D:nodejsfile_uploadserver.js:15:6)
6
at Server.emit (events.js:98:17)
7
at HTTPParser.parser.onIncoming (http.js:2108:12)
8
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23
9
)
10
at Socket.socket.ondata (http.js:1966:22)
11
at TCP.onread (net.js:527:27)
12
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
Advertisement
Answer
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.