Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / readdirp / examples / grep.js
1 'use strict';
2 var readdirp =  require('..')
3   , util     =  require('util')
4   , fs       =  require('fs')
5   , path     =  require('path')
6   , es       =  require('event-stream')
7   ;
8
9 function findLinesMatching (searchTerm) {
10
11   return es.through(function (entry) {
12     var lineno = 0
13       , matchingLines = []
14       , fileStream = this;
15
16     function filter () {
17       return es.mapSync(function (line) {
18         lineno++;
19         return ~line.indexOf(searchTerm) ? lineno + ': ' + line : undefined;
20       });
21     }
22
23     function aggregate () {
24       return es.through(
25           function write (data) { 
26             matchingLines.push(data); 
27           }
28         , function end () {
29
30             // drop files that had no matches
31             if (matchingLines.length) {
32               var result = { file: entry, lines: matchingLines };
33
34               // pass result on to file stream
35               fileStream.emit('data', result);
36             }
37             this.emit('end');
38           }
39       );
40     }
41
42     fs.createReadStream(entry.fullPath, { encoding: 'utf-8' })
43
44       // handle file contents line by line
45       .pipe(es.split('\n'))
46
47       // keep only the lines that matched the term
48       .pipe(filter())
49
50       // aggregate all matching lines and delegate control back to the file stream
51       .pipe(aggregate())
52       ;
53   });
54 }
55
56 console.log('grepping for "arguments"');
57
58 // create a stream of all javascript files found in this and all sub directories
59 readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
60
61   // find all lines matching the term for each file (if none found, that file is ignored)
62   .pipe(findLinesMatching('arguments'))
63
64   // format the results and output
65   .pipe(
66     es.mapSync(function (res) {
67       return '\n\n' + res.file.path + '\n\t' + res.lines.join('\n\t');
68     })
69   )
70   .pipe(process.stdout)
71   ;