Reputation: 23
I have this problem with the path module. When I try to use "path.join..." inside the request handler, I get the error message
TypeError: Cannot read property 'join' of undefined
However, I can fix it by loading the module inside the body of the requestHandler (I commented it out in the code).
Could you explain why it fails and why the "fix" works and what is the most common way to handle this?
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var port = 3000;
var requestHandler = (request, response) => {
//path = require('path');
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
var path = process.cwd();
var buffer = fs.readFileSync(path + "/someSite.html");
response.end(buffer);
};
var server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('sum ting wong', err);
}
console.log('server is listening on ${port}');
});
Upvotes: 2
Views: 1347
Reputation: 14327
It's broken because you're reassigning to path
inside your request handler w/ var path = process.cwd()
.
The var declaration is being hoisted, which means your implementation is equivalent to:
var requestHandler = (request, response) => {
var path; // hoisted!
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
path = process.cwd();
// ...
};
Upvotes: 6