我正在编写一个转换流,它接受一个传入的 XML 流并将其中的一个子集作为 JS 对象发出。
<item>
<name>some name</name>
<files>
<file path='path/to/file'/>
<file path='path/to//other/file'/>
</files>
</item>
需要写两个item对象
{
name: 'some name',
file: 'path/to/file
}
和
{
name: 'some name',
file: 'path/to/other/file
}
因为它将通过管道传输到 CSV 写入器中。
代码看起来像
import fs from 'fs'
import expat from 'node-expat'
import { Transform } from 'stream'
const xParser = (filePath) => {
const stream = fs.createReadStream(filePath)
const parser = new expat.Parser('UTF-8')
const tranny = Transform({ objectMode: true })
tranny._transform = function transform(data, encoding, done) {
this.push(data)
done()
}
let current
let inItem = false
let tag
let attributes
const startTag = (name, attrs) => {
if (name === 'item') {
inItem = true
current = {
name: '',
files: []
}
return
}
if (!inItem) return
tag = name
attributes = attrs
if (tag === 'file') {
current.files.push(attributes.path)
}
}
const write = (file) => {
tranny.write({
name: current.name,
file
})
}
const endTag = (name) => {
if (name === 'item') {
// console.log('end item', JSON.stringify(current))
inItem = false
if (current.files.length === 0) {
write('')
} else {
current.files.forEach(file => {
write(file)
})
}
tag = undefined
attributes = undefined
}
}
const handleText = (text) => {
if (!inItem) return
if (tag === 'name') {
current.name = current.name.concat(text).trim()
}
}
const handleDone = () => {
console.log('done')
tranny.end()
}
parser
.on('startElement', startTag)
.on('endElement', endTag)
.on('text', handleText)
.on('end', handleDone)
stream.pipe(parser)
return tranny
}
module.exports = xParser
当 xml 很简单时
<item>
<name>some name</name>
<files>
<file path='path/to/file'/>
</files>
</item>
这很好用,但是当它遇到item
多个文件时,它就会停止并在第二个发生时'end'
立即触发。tranny.write
如何让转换流为每个输入块发出多条记录?