gpt4 book ai didi

node.js - 使用nodejs中xmlbuilder包中的内置streamWriter

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:51 25 4
gpt4 key购买 nike

我想创建 XML 文件,为此我使用包 xmlbuilder。初始代码工作正常,如下所示:

const xmlStructure = {
// xml structure
};

const root = builder.create(xmlStructure, { encoding: 'utf-8' });

const xml = root.end({ pretty: true });

const readableStream = new Readable();
const writableStream = file.createWriteStream();

writableStream
.on('error', error => {
throw error;
})

.on('finish', async () => {
// do something in the DB
});

readableStream._read = () => {
readableStream.push(xml);
readableStream.push(null);
};

readableStream.pipe(writableStream);

但我在包的 wiki 中看到,streamwriter 中有一个构建。我想将其添加到项目中并删除我在代码中所做的一些自定义操作。

我尝试了以下方法:

const xmlStructure = {
// xml structure
};

const writableStream = file.createWriteStream();

const writer = xmlbuilder.streamWriter(writableStream);

writableStream
.on('error', error => {
throw error;
})

.on('finish', async () => {
// do something in the DB
});


const root = builder.create(xmlStructure, { encoding: 'utf-8' });

const xml = root.end(writer);

const readableStream = new Readable();

readableStream.pipe(writableStream);

不幸的是,这不起作用,我做错了什么或忘记了什么?

最佳答案

缺少的代码行如下:

writableStream.end();

所以最终结果如下所示:

const xmlStructure = {
// xml structure
};

const root = builder.create(xmlStructure, { encoding: 'utf-8' });

const writableStream = file.createWriteStream();

const writer = xmlbuilder.streamWriter(writableStream);

const xml = root.end(writer);

writableStream.end();

writableStream
.on('error', error => {
throw error;
})

.on('finish', async () => {
// do something in the DB
});

关于node.js - 使用nodejs中xmlbuilder包中的内置streamWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com