javascript - Cannot read undefiend of '.html' -
trying create new webserver using nodejs, got error saying .html undefined.
var mimetype = { "html" : "text/html", "jpeg" : "image/jpeg", "jpg" : "image/jpeg", "png" : "image/png", "js" : "text/javascript", "css" : "text/css" }; http.createserver(function(req,res){ var uri = url.parse(req.url).pathname; var filename = path.join(process.cwd(),unescape(uri)); console.log('loading '+uri); var stats; try{ stats = fs.lstatsync(filename); }catch(e){ res.writehead(404, {'content-type':'text/plain'}); res.write('404 not found\n'); res.end(); return; } // check if file/directory if(stats.isfile){ //error happen here var mimetype = mimetype[path.extname(filename)].split(".").reverse()[0]; res.writehead(200, {'content-type': mimetype}); var filestream = fs.createreadstream(filename); filestream.pipe(res); } }).listen(3000);
i'm new node, have no idea how debug. need , guidance.
the problem in these lines:
var mimetype = mimetype[path.extname(filename)].split(".").reverse()[0]; res.writehead(200, {'content-type': mimetype});
there, you're declaring mimetype
variable in scope of createserver
response handler function, making mimetype
@ top of code inaccessible. so, mimetype
undefined
when try property it: mimetype[path.extname(filename)]
rename variable, , should work:
var contenttype = mimetype[path.extname(filename)].split(".").reverse()[0]; res.writehead(200, {'content-type': contenttype });
Comments
Post a Comment