How can I extract filename from gulp-contains call

2019-07-12 19:06发布

问题:

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));
            }
        }))

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 ... >>

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

回答1:

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));
            }
        }))