首页 > 解决方案 > 如何从 gulp-contains 回调中提取文件名?

问题描述

我正在使用 gulp-contains 检查特定字符串,如果找到该字符串,我想抛出一个错误,如“在文件 abc 中找到字符串”。文件参数包含包含文件名+缓冲区的整个对象,但我不知道如何从 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) 也记录输出,如

<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 包含一些字符串,它不应该”

标签: javascriptnode.jsgulp

解决方案


这里的文件是 Node.js 中的一个文件对象。您可以使用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));
            }
        }))

推荐阅读