2016-05-23 73 views
0

使用Gulp我需要搜索我的文件的字符串,并找到该字符串时记录到控制台。吞咽每个错误

当我搜索每个文件中存在的字符串时,以下方法可用。

function logMatches(regex) { 
    return map(function(file, done) { 
    file.contents.toString().match(regex).forEach(function(match) { 
     console.log(match); 
    }); 
    done(null, file); 
    }); 
} 

var search = function() { 
    return gulp.src(myfiles) 
    .pipe(logMatches(/string to search for/g)); 
}, 

然而,如果在每一个文件中的字符串心不是那么我得到的错误:

TypeError: Cannot read property 'forEach' of null 

我知道有从正则表达式匹配的结果,因为他们正在登录到控制台(错误之前) 。

+0

那是'map'功能从一个众所周知的图书馆吗?另外,你能指定一些输入和预期结果吗? –

回答

0

它看起来像你的内联函数被称为多次(我想这就是map应该这样做)。

第一次,正则表达式匹配,正如你在控制台日志中看到的那样。

但第二次,它不匹配。所以,.match(regex)返回null,并且您有效地调用null.forEach(...),因此错误。

尝试调用它forEach之前检查你的正则表达式的结果:

return map(function(file, done) { 
    var contents = file.contents.toString(); 
    var matches = contents.match(regex); 
    console.log(contents, matches); // Here you can see what's going on 
    if(matches) matches.forEach(function(match) { 
     console.log(match); 
    }); 
    done(null, file); 
    });