oozcitak / xmlbuilder-js

An XML builder for node.js
MIT License
918 stars 107 forks source link

Using the streamWriter #227

Closed Emre-Hacilar closed 4 years ago

Emre-Hacilar commented 4 years ago

Hi,

I saw in the wiki, that the xmlbuilder provides a build in streamwriter, and wanted to use this for my project. I tried some stuff but unfortunatly didn't get it to work.

Here is a example code of my project, where I'd like to add the build in streamwriter:

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);
oozcitak commented 4 years ago

You need to create a stream writer with your writable stream and pass it to xmlbuilder. For example:

const xmlStructure = {
    // xml structure
};

const writableStream = file.createWriteStream();

const writer = builder.streamWriter(writableStream);
builder.create(xmlStructure , { encoding: 'utf-8' }).end(writer);

writableStream.end();

writableStream.on('end', function() {
  // do something in the DB
});
Emre-Hacilar commented 4 years ago

Hi oozcitak, thanks for the fast response, your answer did the trick thanks a lot, I guess the missing line of code was to end the writableStream.

But unfortunately, my XML gets generated as on line now, since the builder.end() ignores my pretty true, is there some way I can add it somewhere else or do I just have to pass it differently?

The way I did it is following:

const xml = root.end(writer, { pretty: true });
oozcitak commented 4 years ago

Try this:

const writer = builder.streamWriter(writableStream, { pretty: true });
Emre-Hacilar commented 4 years ago

Yes that did the trick, thanks a lot for your time and help.

oozcitak commented 4 years ago

This should also work:

.
.
.
const writer = builder.streamWriter(writableStream);
builder.create(xmlStructure , { encoding: 'utf-8' }).end({ writer: writer, pretty: true });
.
.
.