如何从gulp包含的回调中提取文件名? [英] How can I extract filename from gulp-contains callback?

查看:243
本文介绍了如何从gulp包含的回调中提取文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gulp-contains检查特定的字符串,如果找到了该字符串,我想抛出诸如在文件abc中找到字符串"之类的错误.文件参数包含整个包含文件名+缓冲区的对象,但是我不知道如何从gulp中的文件对象中提取文件名?

I am using gulp-contains to check for specific string and if that string is found I want to throw an error like "String found in file abc". the file param contains the whole object containing filename + Buffer but I don't know how can I extract filename from file object in gulp?

 .pipe(contains({
            search: 'myString',
            onFound: function (string, file, cb) {
                console.log(file);
                var error = 'Your file "' + file + '" contains "' + string + '", it should not.';
                cb(new gutil.PluginError('gulp-contains', error));
            }
        }))

现在,此行给出的输出为您的文件[object Object]包含someString,但不应包含". 同样console.log(file)记录输出,例如

Now this line gives the output as "Your file [object Object] contains someString, it should not". Also console.log(file) logs the output like

<File "myFile.js"  <Buffer 66 75 6e 63 74 69 6f 6e 20 28 75 73 65 72 2c 20 63 6f 6e 74 65 78 74 2c 20 63 61 6c 6c 62 61 63 6b 29 20 7b 0d 0a 20 20 20 20 63 6f 6e 73 6f 6c 65 2e ... >>

我只想要"myFile.js"部分,因此我的输出字符串将是您的文件myFile.js包含someString,但不应包含"

I just want the part "myFile.js" so my output string would be "Your file myFile.js contains someString, it should not"

推荐答案

此处的文件是Node.js中的文件对象.您可以使用 file.path

The file here is a file object in Node.js. You can get the path using file.path

.pipe(contains({
            search: 'myString',
            onFound: function (string, file, cb) {
                console.log(file);
                var sFile = require('path').parse(file.path).base;
                var error = 'Your file "' + sFile + '" contains "' + string + '", it should not.';
                cb(new gutil.PluginError('gulp-contains', error));
            }
        }))

这篇关于如何从gulp包含的回调中提取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆