How can I extract filename from gulp-contains callback?

主宰稳场 提交于 2019-12-12 19:14:50

问题


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


来源:https://stackoverflow.com/questions/51303941/how-can-i-extract-filename-from-gulp-contains-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!