在 gulp 中,我将多个文件解析为对象数组;然后我想将所有这些数组合并为一个,并根据合并后的数组输出一个文件。
file1 parsed into array1
file2 parsed into array2
file3 parsed into array3
combinedArray = array1 + array2 + array3
combinedArray used to generate outputFile
我不确定如何使用 gulp 将三个数组组合成一个数组 - 我想我想减少或折叠流元素。
鉴于这些功能,您将如何编写?
parseFile(file)
返回一个数据对象数组createFile(objects)
从数据对象数组创建一个文件对象
我确信这很简单,但我并不是通过猜测正确的搜索词来找到答案。对node不是很熟悉...
这个问题的一个人为的例子是有几个满是名字的文件;从每个文件中提取以“B”开头的名称;然后输出一个按字母顺序排列的、去重复的名称列表,以“B”开头。所以它不仅仅是文件的串联,它是解析成一个数据结构并将数据结构组合成一个,然后根据组合输出一个文件。
最佳答案
您必须使用一些有趣的插件... 我已经在下面实现了您的“B-names”要求:
在第一步中,我将每个输入文件的内容转换为一个 JSON 字符串,该字符串将所有“B”名称作为键,将“true”作为值(类似于 Set,消除重复项)。
在第二步中,我将所有文件“缩减”为一个文件。 (这有点像函数式编程中的“reduce”)。每个文件的内容从 JSON 转换回一个对象,并且所有键都合并到一个最终对象中(再次消除文件之间的重复项)。 “reduce”的最后一步从最终对象中提取它们的键,对它们进行排序,然后将它们全部放入一个名为“b_names”的文件中。
(此代码是 Coffeescript)
gulp = require 'gulp'
transform = (require 'gulp-insert').transform
reduce_file = require 'gulp-reduce-file'
gulp.task 'parse_and_merge', ->
gulp.src 'names*', cwd:'./input'
.pipe transform (contents,file)->
b_names = {}
for b_name in contents.match /B\w+/igm
b_names[b_name] = true
return JSON.stringify b_names
.pipe gulp.dest 'output' # not required, but maybe informative
.pipe reduce_file 'b_names',
(file,memo)->
this_nameset = JSON.parse(file.contents)
for key,val of this_nameset
memo[key] = true
return memo
,(memo)->
b_names = Object.keys(memo)
b_names.sort()
return b_names.join('\n')
,{}
.pipe gulp.dest 'output'
names1:
John
Bob
Charles
names2:
Joe
Buster
Michael
names3:
Jacob
Barack
Keith
Bob
Bob
b_names:
Barack
Bob
Buster
关于javascript - gulp中解析多个文件生成一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526510/