node.js 即使在返回 false 时也处理数组检查失败条件

node.js array check fails conditional is processed even while returning false

我在 node.js 中有一个缓冲区,我正在使用正则表达式检查 mime 类型。
正则表达式中有一个捕获组,如果它成功,它必须 return 数组中索引 1 处的这个捕获组 return 由 exec.

编辑

我正在使用

if(mime.exec(dt)[1]){
    tip.push(mime.exec(dt)[1]);
}

这个控件我也试过了

if(1 in mime.exec)

还有

mime.exec.hasOwnProperty(1)

但不管怎样,条件都会被处理并给出回溯

TypeError: Cannot  read property '1' of null

我可以使用什么样的机制来解决这个问题?

更新----

var mime=/^内容类型:(.+\S)/igm;

更新----

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)

没有更多上下文(尤其是 mime 的值是如何赋值的),很难说到底发生了什么,但我们可以肯定地说:mime.execnull 在您的代码执行时 mime.exec.hasOwnProperty(1)。因此,启动调试器并观察 mime 的值以了解发生了什么。

问题是您的正则表达式设置了 global 标志 - 比较 Why RegExp with global flag in Javascript give wrong results?。因此,当您第一次调用 mime.exec(dt) 时,它会匹配某些内容并推进 mime.lastIndex 属性,但是当您第二次调用 mime.exec(dt) 时,它 不会在 dt 字符串中找不到第二个匹配项

所以有两件事要做:

  • 如果您只想进行一次匹配,请不要将其设为 global 正则表达式。
    或者,如果您打算重用该对象(例如示例中的多个回调调用),请确保每次都用尽搜索(通常 while (m = regex.exec(input)))或重置 regex.lastIndex=0;
  • 不要调用exec()两次,只是将结果存储在一个变量中

还要注意 .exec() 可能根本就不是 return 数组,而是 null 当它不匹配任何东西时,所以无论如何你都必须使用

var match = mime.exec(dt);
if (match) // possibly `&& match[1]` if you need to ensure that no empty string was captured
    tip.push(match[1]);

改变这个

if (mime.exec(dt)[1]) {

至此

if (mime.exec(dt) && mime.exec(dt)[1]) {

exec returns null 或数组——首先测试 null,因为您不能将 null 视为数组。

编辑: 如评论中所述,如果使用全局正则表达式,可能需要牢记其他注意事项。

因此,对于全局正则表达式,超级安全版本:

var rslt = mime.exec(dt)
if (rslt && rslt[1]) {
  tip.push(rslt[1]);