javascript - node.js array check fails conditional is processed even while returning false -
i have buffer in node.js , i'm checking mime type regex.
there capturing group in regex , if successfull must return capturing group @ index 1 in array returned exec.
i'm using
if(mime.exec(dt)[1]){ tip.push(mime.exec(dt)[1]); }
this control , tried
if(1 in mime.exec)
and
mime.exec.hasownproperty(1)
but anyway condition processed , gives traceback
typeerror: cannot read property '1' of null
what kind of mechanism can use fix issue?
update ----
var mime=/^content-type: (.+\s)/igm;
update ----
var fs = require("fs"), mime = /^content-type: (.+\s)/igm, tip = []; require("http").createserver(function(req, res) { var data = ""; console.log("working..."); console.log(req.method); if (req.method.touppercase() == "post") { req.once("data", function() { fs.writefilesync("dene.txt", ""); }); req.on("data", function(dt) { fs.appendfilesync("dene.txt", dt.tostring("utf8")); if (mime.exec(dt)[1]) { tip.push(mime.exec(dt)[1]); } else { return false; } }); req.on("end", function() { console.log(((fs.statsync("dene.txt").size) / 1024).tofixed(2), "kb"); console.log(tip); }); } res.writehead(200, { "content-type": "text/html" }); res.end(require("fs").readfilesync(require("path").resolve(__dirname, "static_files/post.html"))); }).listen(3000)
change this
if (mime.exec(dt)[1]) {
to this
if (mime.exec(dt) && mime.exec(dt)[1]) {
exec
returns either null or array -- test null first because can't treat null array.
edit: mentioned in comments, there additional considerations keep in mind if using global regex.
so, global regexes, super-safe version:
var rslt = mime.exec(dt) if (rslt && rslt[1]) { tip.push(rslt[1]);
Comments
Post a Comment